我终于让我的Rails待办事项列表应用使用Backbone的渲染器来显示待办事项了。不过我有一个小问题。在addOne函数中,我使用了view.render()而不是view.render().el,这是在教程中教过的。
这个视图不能用view.render.el()来呈现,有什么解释吗?
$(function(){
Todos = new TodoList.Collections.Todos;
TodoList.Views.TodoView = Backbone.View.extend({
tagName: "li",
events: {},
initialize: function(){},
template: _.template('<li> <%= task %></li>'),
render: function(){
var todo = this.model.toJSON();
return this.template(todo);
}
});
TodoView = TodoList.Views.TodoView;
TodoList.Views.AppView = Backbone.View.extend({
el: $("#todo_app"),
events: {
"submit form#new_todo": "createTodo"
},
initialize: function(){
_.bindAll(this, 'addOne', 'addAll','render');
Todos.bind("add", this.addOne);
Todos.bind("reset", this.addAll);
Todos.bind("all", this.render);
Todos.fetch();
},
addOne: function(todo){
var view = new TodoView({model: todo});
this.$("#todo_list").append(view.render());
},
addAll: function(){
Todos.each(this.addOne);
},
newAttributes: function(event){
var new_todo_form = $(event.currentTarget).serializeObject();
return {
dog: {
name: new_todo_form["todo[task]"],
age: new_todo_form["todo[done]"]
}
};
},
createTodo: function (e){
e.preventDefault();
var params = this.newAttributes(e);
Dogs.create(params);
}
});
});
2条答案
按热度按时间whlutmcx1#
如果您要对
console.log
调用的每个组件执行以下操作,则输出将类似于以下内容:所以你不能调用
el
,因为它只是一个属性实际上它是一个HTMLElement
对象。在你的代码中你是returning html
。如果你通过view.render链接调用().el您必须使用this
关键字返回示例。当您返回instance
时,您可以访问所有instance
'所以,当你返回html
时,你不能链接视图对象,这就是为什么在演示中,它们返回this
。无论如何,你都不应该返回视图的html,你总是想通过
el
或$el
属性来访问Backbone的html。zfycwa2u2#
el
不是函数,而是构成视图的HTML。调用render()
通常会生成HTML并将其存储在el
属性中。按照约定,此方法应返回this
,以允许您直接引用对象(并用于链接)。因此,
view.render().el
将呈现该元素并返回适合附加到DOM的HTML。