我试图构建一个带有附加小部件作为 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, output
如果我执行以下操作,它会起作用:
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,output
我究竟做错了什么?提前致谢!