[英]Ember.js – Binding a button action from an #each loop to its own model
我似乎無法在#each
模板循環中生成一個按鈕,將其單擊操作綁定到其關聯的模型。 這是問題的快速演示......
Ember.js
應用程序設置:
window.Contacts = Ember.Application.create();
Contacts.Person = Ember.Object.extend({
first: '',
last: '',
save: function() {
// send updated information to server.
}
});
Contacts.contactsList = Ember.ArrayController.create({
content:[],
init: function() {
this.pushObject( Contacts.Person.create({
first:'Tom',
last:'Riddle'
}));
}
});
模板:
<script type="text/x-handlebars">
{{#each Contacts.contactsList}}
<li>
{{view Ember.TextField valueBinding="first" viewName="firstname"}}
{{view Ember.TextField valueBinding="last" viewName="lastname"}}
<button {{action "save" on="click"}}>Save</button>
</li>
{{/each}}
</script>
問題:
因此,在這個簡單的演示場景中的想法是每個記錄的“保存”按鈕將觸發一個動作來保存自己模型的狀態。 但是,單擊“保存”按鈕會出錯:
Uncaught TypeError: Cannot call method 'call' of undefined
我的假設是將“save”指定為按鈕的動作會將其綁定到其模型上的save
方法。 但是,情況似乎並非如此。 其他一些對象似乎是處理點擊操作,其中未定義“保存”處理程序。 我在這里錯過了什么嗎? 如何讓每個訂單項的按鈕調用自己的模型上的處理程序?
在此先感謝您的幫助!
您可以通過設置 - surprise - target
屬性來定義操作的target
,請參閱http://jsfiddle.net/pangratz666/FukKX/ :
<script type="text/x-handlebars" >
{{#each Contacts.contactsList}}
<li>
{{view Ember.TextField valueBinding="first" viewName="firstname"}}
{{view Ember.TextField valueBinding="last" viewName="lastname"}}
{{#with this as model}}
<button {{action "save" target="model"}}>Save</button>
{{/with}}
</li>
{{/each}}
</script>
需要圍繞操作的{{#with}}
幫助程序,因為操作助手不會以某種方式接受this
作為target
。
但請注意您的設計:應該在視圖或控制器上調用操作。 然后目標負責執行保存等進一步的操作......
所以我將按如下方式實現您的示例,請參閱http://jsfiddle.net/pangratz666/U2TKJ/ :
把手 :
<script type="text/x-handlebars" >
{{#each Contacts.contactsList}}
<li>
{{view Ember.TextField valueBinding="first" viewName="firstname"}}
{{view Ember.TextField valueBinding="last" viewName="lastname"}}
<button {{action "save" target="Contacts.contactsController" }}>Save</button>
</li>
{{/each}}
</script>
JavaScript :
Contacts.contactsController = Ember.Object.create({
save: function(event) {
console.log('do something with: ', event.context);
}
});
有兩種可能的方法
{{#each answer in effort_reasons itemController="module_answer"}}
{{/each}}
因此每個Item都有自己的控制器,其中model是每個項目(在本例中為答案),這對於像InputView這樣的東西特別有用,其中valueBinding會導致將每個輸入視圖綁定到相同的值。 請注意,這是Ember中的控制器不是單例,並且具有不同ID的唯一時間,如果要將值保存在原始控制器中,則可以通過
this.get('controller.parentController')
在你的itemController里面。
或者你在每個循環中使用上面提到的動作方法
{{action "actionname" parameter paramter2...}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.