backbone.js - 处理 underscore.js 模板中的未定义属性

标签 backbone.js underscore.js

我正在 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/

相关文章:

javascript - 设置 Backbone 集合中所有模型的属性

ruby-on-rails - 使用 Backbone.js 加载模型关系

node.js - 将 Jquery UI 与express.js 结合使用

javascript - 使用下划线js按嵌套数组项拼合数组

javascript - 过滤带下划线的对象数组并获取新的值数组

javascript - lodash、分组和计数

javascript - AJAX + Rails 的最新技术是什么?

jquery - 将带有对象的数组转换为 JSONstring

javascript - 使用下划线和 jquery 在 javascript 中自动填充表格

javascript - 从对象键创建正则表达式