我正在寻找一种解决方案,将包含字符串数组(表示服务器上的枚举)的对象属性绑定到复选框列表.绑定应该是双向的.
在服务器上,我们有一些枚举定义,例如,具有值"ADMIN","GUEST","USER"的角色.用户对象可以具有多个这样的角色,因此Ember中的用户对象具有该形式
App.User = Ember.Object.create({
roles: ["USER", "ADMIN"]
});
Run Code Online (Sandbox Code Playgroud)
在用户管理中,应该有一组复选框.每个角色一个复选框.因此,可以选择无,全部或几个.
我知道有Ember.Checkbox可以用于此的视图.我正在寻找的是一个简单而通用的视图来处理上面提到的任何类型的枚举.
因此,问题是:
提前致谢.// ph
如果您愿意手动同步服务器和客户端上的枚举(使用AJAX或WebSockets),则可以使用普通Ember.js实现处理Ember对象和Checkbox之间的双向绑定的通用方法,而无需任何插件.请注意,Ember可以在同步后自动使用Checkbox更新选项列表.
所以今后,我将假设你有一个作为Ember数组角色的枚举:
App.Roles = [ "USER", "ADMIN", "GUEST" ];
Run Code Online (Sandbox Code Playgroud)
然后我们将在这样的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
})
});
Run Code Online (Sandbox Code Playgroud)
每个选项的模板是:
<script data-template-name="user-roles" type="text/x-handlebars">
<label> {{view App.RoleCheckbox
contentBinding="view.content"}}
{{view.content}}
</label>
</script>
Run Code Online (Sandbox Code Playgroud)
请注意,使用<label>标记可确保click在单击标记上的任何位置时触发Checkbox的事件.
最后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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
一个工作示例是:http://jsfiddle.net/BLQBf/(查看控制台以查看日志消息)
请注意,这不完全是Ember-esque,因为View正在执行部分工作controller.理想情况下,click事件会调用一个函数RoleCheckboxController来User对象进行更改.