Ember オブジェクトとチェックボックス間の双方向バインディングを処理する一般的な方法は、サーバーとクライアントの列挙型を手動で (AJAX または WebSocket を使用して) 同期する場合、プラグインを必要とせずにプレーンな Ember.js を使用して実装できます。 . Ember は、同期後に Checkbox を使用してオプションのリストを自動的に更新できることに注意してください。
したがって、今後は、Ember Array としてロールを持つ列挙型があると仮定します。
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', 'userRoles.@each'),
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/ (ログメッセージを見るためにコンソールを見てください)
ビューはcontroller
. 理想的には、click
イベントは、オブジェクトRoleCheckboxController
に変更を加える関数を呼び出します。User