Shared state in Ember component

前端 未结 2 1688
被撕碎了的回忆
被撕碎了的回忆 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:27

    After you declare the component, each time you use it in your template a new instance will be created, and most importantly the init hook will also be called every time a new instance is instantiated, therefore the most secure way to have different myList arrays would be to use the component init hook, to initialize the array, so try the following:

    App.AppendableListComponent = Ember.Component.extend({
      myList: null,
      init: function(){
        this._super();
        this.set('myList', Ember.ArrayProxy.create({content: []}));
      },
      actions: {
        append: function(){
          var newItem = this.get('newItem');
          this.get('myList').pushObject(newItem);
        }
      }
    });
    

    Also important is to call this._super(); inside init and everything will work as expected.

    See here for a working demo.

    Hope it helps.

提交回复
热议问题