我正在 View 中渲染单个 Backbone 模型。我使用默认的下划线模板来渲染模型。渲染 View 时如何处理“未定义”属性错误(尽管模型尚未加载)?为了澄清,这里是一个例子。
// Using Mustache style markers
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};
App.Model = Backbone.Model.extend({});
App.Collection = Backbone.Collection.extend({
model: App.Model
});
App.View = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.template = _.template($('#model_template').html());
this.model.bind('reset', this.render);
},
render: function() {
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
// HTML
<div id="container"></div>
<script id="model_template" type="text/template">
<strong>Name:</strong> {{ name }} <br/>
<strong>Email:</strong> {{ email }} <br/>
<strong>Phone:</strong> {{ phone }}
</script>
// Run code
var collection = new App.Collection;
var view = new App.View(model: collection.at(0));
$('#container').html(view.render().el);
collection.fetch();
运行此代码时, View 会呈现两次,第一次使用空模型,第二次在 AJAX 查询完成时(并触发“重置”)。但是我面临的问题是 JS 在模型为空时首先停止。它给出了一个错误,说模型属性未定义。
我在这里做错了什么?当 View 在第一个实例中呈现时,我可以抑制“未定义”错误吗?
最佳答案
一种选择是为您的模型定义默认的空值。
App.Model = Backbone.Model.extend({
defaults: {
name: '',
email: '',
phone: ''
}
});
关于backbone.js - 处理 underscore.js 模板中的未定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348906/