如果您願意同步服務器和客戶端上的枚舉,則可以使用普通的Ember.js實現處理Ember對象和複選框之間雙向綁定的通用方法,而無需任何插件手動(使用AJAX或WebSockets)。請注意,Ember可以在同步後自動使用複選框更新選項列表。
所以從今以後,我會假設你有一個角色灰燼陣列上午枚舉:
App.Roles = [ "USER", "ADMIN", "GUEST" ];
然後,我們將展示在CollectionView這樣對用戶可用的選項(模板如下)。
OptionsView = Em.CollectionView.extend({
contentBinding: 'App.Roles', // Show a list of _all_ available roles
userBinding: 'App.User', // This points to the active user
tagName: 'ul', // Shown as a <ul>
itemViewClass: Em.View.extend({
userBinding: 'parentView.user', // For convenience
templateName: 'user-roles' // Defined later
})
});
每個選項的模板是:
<script data-template-name="user-roles" type="text/x-handlebars">
<label> {{view App.RoleCheckbox
contentBinding="view.content"}}
{{view.content}}
</label>
</script>
注意的是,使用<label>
標籤可確保複選框的click
事件上點擊標籤的任何地方發射。
最後App.RoleCheckbox
是Ember.Checkbox
類的擴展,處理checked
財產和click
事件來切換角色:這
App.RoleCheckbox = Em.Checkbox.extend({
userRolesBinding: 'parentView.user.roles', // Points to the roles of the user
checked: function() {
var userRoles = this.get('userRoles');
return userRoles.contains(this.get('content'));
}.property('content', '[email protected]'),
click: function (evt) {
var isPresent = this.get('checked'),
userRoles = this.get('userRoles'),
role = this.get('content');
if (!isPresent) {
userRoles.pushObject(role);
} else {
userRoles.removeObject(role);
}
}
});
一個工作的例子是:http://jsfiddle.net/BLQBf/(查看控制檯看日誌消息)
請注意,這不是完全Ember式的,因爲視圖正在爲controller
做一部分工作。理想情況下,click
事件將調用RoleCheckboxController
上的函數,該函數將更改User
對象。
感謝@musically_ut的答案。我不得不推遲我的這個實施,所以我的評論來得晚。你的解決方案有效,但有一個小問題。點擊事件之前觸發'checked'的觀察者。在那裏,我不得不還原由click事件觸發的if-else語句。 –
@musically_ut,我問了一個關於如何調用RoleCheckboxController的問題,正如你所建議的[這裏](http://stackoverflow.com/questions/16281401/ember-how-to-create-and-bind-a-複選框控制器),但我無法使它工作。 – lauhub
已經觸發了對@musically_ut回答的編輯。它目前是同行評議的。直到它被審查。由於瀏覽器的兼容性,請使用「更改」事件而不是「點擊」事件。另見https://github.com/emberjs/ember.js/issues/2604 –