Ember 组件中的共享状态

2023-11-26

我试图构建一个简单的列表,其中附加小部件作为 Emberjs 组件。

以下是我使用的代码:

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ember.js/1.0.0/ember.min.js"></script>
<meta charset=utf-8 />
<title>Ember Component example</title>
</head>
<body>

  <script type="text/x-handlebars" id="components/appendable-list">
     <h2> An appendable list </h2>
     <ul> 
       {{#each item in myList}}
         <li> {{item}} </li>
       {{/each}} 
     </ul>
     {{input type="text" value=newItem}}
     <button {{action 'append'}}> Append Item </button>
  </script>

  <script type="text/x-handlebars">
    {{appendable-list}}
    {{appendable-list}}
  </script>

</body>
</html>

JavaScript:

App = Ember.Application.create();

App.AppendableListComponent = Ember.Component.extend({
    theList: Ember.ArrayProxy.create({ content: [] }),
    actions: {
        appendItem: function(){
            var newItem = this.get('newItem');
            this.get('theList').pushObject(newItem);
        }
    }
});

在这种情况下,该列表在两个实例之间共享(即,在一个实例中追加在另一个实例中追加)

这是 JsBin 来检查一下:http://jsbin.com/arACoqa/7/edit?html,js,输出

如果我执行以下操作,它会起作用:

window.App = Ember.Application.create();

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

这是 JsBin:http://jsbin.com/arACoqa/8/edit?html,js,输出

我究竟做错了什么?提前致谢!


声明组件后,每次在模板中使用它时都会创建一个新实例,最重要的是init每次实例化新实例时也会调用钩子,因此最安全的方法是拥有不同的实例myList数组将使用该组件init钩子,初始化数组,所以尝试以下操作:

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);
    }
  }
});

同样重要的是打电话this._super(); inside init一切都会按预期进行。

请参阅此处的工作demo.

希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ember 组件中的共享状态 的相关文章

随机推荐