我想将额外的变量传递给我的模板,即一些不包含在模型中的变量。这些基本上是显示参数,例如屏幕接下来将如何显示给用户。它不必保存在数据库中。
我试过了,但似乎不起作用:
render: function () {
this.extra_list = _.shuffle(this.extra_list);
jQuery.extend(this.model, this.extra_list);
this.$el.html(this.template(this.model.toJSON()));..
return this;
}
当我在模板中引用 extra_list 时,出现变量未定义的错误。我错过了什么?
最佳答案
model.toJSON()
返回模型的属性 而不是属性。由于您的扩展函数将这些属性直接添加到模型中,因此当您将 toJSON
的输出传递给您的模板时,它们是未定义的。
要么将 extra_list
添加到您的模型的属性中(听起来您不想这样做),要么将 toJSON
的输出与 extra_list
并将其传递给您的模板。
编辑:如评论中所述,您可以使用 _.extend
将 extra_list 与模型的属性“合并”:
render: function () {
this.extra_list = _.shuffle(this.extra_list);
var data = _.extend(this.model.toJSON(), this.extra_list);
this.$el.html(this.template(data));
return this;
}
关于javascript - Backbone 在将模型渲染到模板之前扩展模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18708696/