我对骨干有点陌生,我很难理解如何设置视图的属性。我使用的是没有模型的视图。
这是一种观点:
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不是一个函数
,如果我第一次尝试它,它就不会调用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());
});
}
我试着把这个包括进去。初始化函数中的render()。不起作用。甚至不调用渲染函数。为什么?
有几件事:
set
不是骨干视图的函数。检查APInew operationErrorView(...)
不会自动调用渲染
函数。你必须手动完成。属性
属性没有get
方法。再次,检查API那么,你该怎么做呢?
研究使用属性初始化视图的不同方法。然后找出如何在视图控制的HTML上获取这些属性。
这里有一点可以让你开始
var OperationErrorView = Backbone.View.extend({
tagName: 'h3',
initialize: function(attributes) {
this.attributes = attributes;
this.render();
},
render: function(){
// attach attributes to this.$el, or this.el, here
// insert the element into the DOM
$('#formAdd_errors').append(this.$el);
}
});
// later in your code
if ( errors.length > 0 ) {
errors.forEach(function(error) {
new OperationErrorView({ error: error });
});
}
感谢chazsolo的回答,所有的信息都在那里。因此,我将编写代码,以防有人发现它有用处:
var OperationErrorView = Backbone.View.extend({
initialize: function(attributes){
this.attributes = attributes;
},
render: function(){
var html = "<h3>" + this.attributes.error +"</h3>";
$(this.el).html(html);
}
});
if (errors.length > 0){
errors.forEach(function(error){
var errorView = new OperationErrorView({'error':error});
errorView.render()
$("#formAdd_errors").append(errorView.$el.html());
});
}