문제

I've spent a lot of time debugging strage error in my component. That component have disabled/enabled buttons, but I haven't seen the effect. After a while, I've noticed, the buttons are changed in the last component instance I've created. The declaration looks so:

  constructor: function(options) {
    for(var i in options){
      this[i] = options[i];
    }
  },
  domNode: null,
  grid: null,
  data: [],
  buttons: {},

In the debug, I've seen, that when I create second instance of my object:

new CustomComponent({domNode: dojo.byId('secondid')})

the buttons are already set - their instance is shared by all instances!

In end effect, I've created a static variable in my component. This is not what I wanted! What is wrong in that declaration? How should I made 'buttons' instance separate for each component instance?

도움이 되었습니까?

해결책

I suppose that CustomComponent is a widget? Then you're doing some stuff wrong. The thing you do in your constructor (I suppose that's to populate your widget properties?) is not even necessary since that's already there by default when you use dijit/_WidgetBase.

Same with your property domNode, it's also there already by default if you use dijit/_WidgetBase.

My guess is that by overriding the constructor to act like this, you're actually doing some steps that the WidgetBase should do and thus messing up the private scope of the properties.

An example widget:

var CustomComponent = declare("my/CustomComponent", [WidgetBase], {
    grid: null,
    data: [],
    buttons: {}
});

This code does exactly the same as your widget and is a lot shorter.

An example JSFiddle that has instance scoped properties (as you can see in the console log).

다른 팁

I've inspected the problem more exact. The problem is, that the declare block is executed only once, therefore creating object prototype, which values are copied to instances.

So when I do buttons: {}, I create Object, which is then copied to all children. In end effect, all children have the same buttons instance - I've created a quasi-static field.

All bugs where gone when I've created the object in the constructor:

  constructor: function(options) {
    for(var i in options){
      this[i] = options[i];
    }
    this.buttons = {}
    this.data = []
  },

Now every instance of my component have own buttons object.

In fact, my problem was exactly described here:

dojo.declare("my.classes.bar", my.classes.foo, {
  someData: [1, 2, 3, 4], // doesn't do what I want: ends up being 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top