Backbone View extends is polluted

2019-02-26 08:36发布

I have a view that represents a modal. This view has some attributes, like the footer extra class. I'm having a trouble that, when some modal change it's value, all of them receive the same attribute.

This is the example:

var ModalView = AlertingView.extend({
    className : "modal",
    paramsTemplate: { footerClass: "" }   
});

After that, I used the modal that has the changed attribute.

SpecialModal = ModalView.extends({
    initialize: function() {
       this.paramsTemplate.footerClass = "white";
    } 
})

So, if I instanciate a normal Modal, this parameter is set! :'(

NormalModal = ModalView.extends({
    initialize: function() {
       console.log(this.paramsTemplate.footerClass);//shows 'white'!
    } 
})

Do you have any idea of how solving it? thanks!

1条回答
男人必须洒脱
2楼-- · 2019-02-26 09:35

http://jsfiddle.net/JQu5Q/11/

This fiddle demonstrates your problem.

As long as you've not created any instance of SpecialModal every instance of NormalModal works.

This is because paramsTemplate is a class variable, not an instance variable. As soon as an instance of SpecialModal is created, it updates the classVariable and hence, all objects reflect that change.

Fortunately, I've just had a similar issue few days back Backbone.js view instance variables?

Solution :

http://jsfiddle.net/JQu5Q/12/

var ModalView = Backbone.View.extend({
    className : "modal",
    initialize:function(){
        this.paramsTemplate= { footerClass: "" }   ;
    }
});
SpecialModal = ModalView.extend({
    initialize: function() {
       ModalView.prototype.initialize.call(this);
       this.paramsTemplate.footerClass = "white";
        console.log(this.paramsTemplate.footerClass);
    } 
})
NormalModal = ModalView.extend({
    initialize: function() {
        ModalView.prototype.initialize.call(this);
       console.log(this.paramsTemplate.footerClass);
    } 
})
查看更多
登录 后发表回答