【发布时间】:2015-02-09 04:13:24
【问题描述】:
我是 Backbone 的新手,我无法理解如何设置视图的属性。我正在使用没有模型的视图。
这是视图:
var OperationErrorView = Backbone.View.extend({
attributes: {},
render: function(){
var html = "<h3>" + this.attributes.get("error") +"</h3>";
$(this.el).html(html);
}
})
后来:
if (errors.length > 0){
errors.forEach(function(error){
// var errorView = new OperationErrorView({attributes: {"error": error} }); Doesn't work
var errorView = new OperationErrorView();
errorView.set({attributes: {"error": error}})
errorView.render()
$("#formAdd_errors").append(errorView.$el.html());
});
}
执行此操作的正确方法是什么?现在它不起作用:当我尝试未注释掉的方法时,它给了我错误TypeError: errorView.set is not a function,如果我尝试第一种方法,它只是不调用 render() 函数。
更新:
var OperationErrorView = Backbone.View.extend({
attributes: {},
initialize: function(attributes){
this.attributes = attributes;
},
render: function(){
var html = "<h3>" + this.attributes.get("error") +"</h3>";
console.log("html");
$(this.el).html(html);
}
})
if (errors.length > 0){
errors.forEach(function(error){
console.log(error);
var errorView = new OperationErrorView({"error": error});
errorView.render()
$("#formAdd_errors").append(errorView.$el.html());
});
}
我尝试在初始化函数中包含 this.render()。不工作。甚至不调用渲染函数。为什么?
【问题讨论】: