Shared state in Ember component

前端 未结 2 1698
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 19:48

I was trying to build a simple list with append widget as an Emberjs component.

The following is the code I used:

HTML:

         


        
2条回答
  •  忘掉有多难
    2021-01-05 20:41

    When you use extend(hash) any value present in the hash, will be copied to any created instance. And because array is a object, your reference will be the same across the created objects:

    App.MyObject = Ember.Object.extend({ text: [] });
    
    obj1 = App.MyObject.create();
    obj2 = App.MyObject.create();
    
    obj1.get('text') === obj2.get('text') // true
    
    obj1.get('text').pushObject('lorem');
    obj1.get('text'); // ["lorem"]
    
    obj2.get('text').pushObject('ipsum');
    obj2.get('text'); // ["lorem", "ipsum"]
    

    The didInsertElement is called for each new view created, and each view is a diferent instance. So with your implementation you always will have a new Ember.ArrayProxy instance for each view, then no shared state exist:

    didInsertElement: function() {
        // each call for this method have a diferent instance
        this.set('myList', Ember.ArrayProxy.create({content: []}));
    }
    

提交回复
热议问题