不要在视图中包含模型属性
Backbone.js don't include model properties in view
我在Backbone.js中有一个模型,如下所示:
Attribute = Backbone.Model.extend({
defaults: {
label: '',
values: {},
},
});
这个视图:
AttributeView = Backbone.View.extend({
tagName: 'button',
className: 'btn',
initialize: function(attribute) {
this.attribute = attribute;
this.render();
},
render: function() {
var template = _.template($("#attribute-template").html(), {attribute: this.attribute});
this.$el.html(template);
},
});
HTML模板:<!----- attribute template ----->
<script type="text/template" id="attribute-template">
<span class="attr">
<%= attribute.get('label') %>
</span>
<span class="badge pull-right"></span>
</script>
结果是:
<button label="..." values="[object Object],[object Object],..." class="btn">...</button>
我的问题是为什么backbonejs添加标签和值属性到html模板,我怎么能防止这种情况?
你已经糟糕地选择了属性来保存你的模型(为什么你在自定义属性中存储你的模型也超出了我的范围),因为Backbone.View.attributes是一个属性,它意味着指定HTML属性添加到视图的el(这是你的<button>
标签- http://backbonejs.org/#View-attributes.
通常,您可以通过在model属性中指定模型的新实例来将模型与视图关联起来,如下所示。然后您可以将模型引用为this.model
,如果您只需要数据,则引用为this.model.toJSON()
:
AttributeView = Backbone.View.extend({
model: new Attribute(),
tagName: 'button',
className: 'btn',
initialize: function() {
this.render();
},
render: function() {
var template = _.template($("#attribute-template").html(), this.model.toJSON());
this.$el.html(template);
},
});
供参考,这里有一个正确使用属性属性的例子:
AttributeView = Backbone.View.extend({
model: new Attribute(),
tagName: 'button',
className: 'btn',
attributes: {
'data-foobar': "I'm a custom data attribute"
}
initialize: function() {
this.render();
},
render: function() {
var template = _.template($("#attribute-template").html(), this.model.toJSON());
this.$el.html(template);
},
});
这将生成:
<button data-foobar="I'm a custom data attribute" class="btn">...</button>
原来我初始化视图时不正确。我直接传入模型
var itemView = new ItemView(item)
我需要将它声明为模型
var itemView = new ItemView({model: item})
也没有意识到属性是一个视图属性,所以我不得不重命名我的模型和视图
相关文章:
- 使用包含过滤器在环回中连接两个模型
- 从包含ng的字段中获取表单数据,而无需使用ng模型
- “角度形状”复选框最初未包含在模型中
- Select选项包含在验证模型MVC时不起作用
- mocking和测试指令,隔离范围包含ng模型
- 我们如何处理包含带有秘银的子数组的数据模型
- 从包含的视图模型访问组件视图模型
- 挖空.js访问包含视图模型中的容器模型属性
- 在模型上使用 JSON.stringify 时,主干集合不包含在 JSON 字符串中
- 为什么我的主干集合包含一个空的模型项
- 如何使用强循环过滤包含“模型”中的数据
- 在Protractor中,我们如何迭代并为包含$index的角度模型赋予不同的值
- 角度模型放宽了指令中包含ng的范围
- 如何在主干模型中正确实现解析以包含集合
- AngularJS我正在尝试计算嵌套ng重复中包含的许多输入(ng模型)的结果
- 模型值包含不必要的文本
- Backbone.js:包含多个具有相同ID的模型的集合
- 如果模型包含使用findWhere存在的键,则返回主干模型
- Js-data在一条路由中包含多个模型
- 不要在视图中包含模型属性