我試圖用附加部件構建一個簡單列表作爲Emberjs組件。Ember組件中的共享狀態
以下是我使用的代碼:
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
我在做什麼錯?提前致謝!
太棒了!我認爲你的方式更清潔。謝謝! – tcbpg
糟糕!我可以發誓我做到了。希望它是固定的。 – tcbpg