backbone.js 为什么视图不使用.el渲染?

mfuanj7w  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(138)

我终于让我的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);
    }
});
});
whlutmcx

whlutmcx1#

如果您要对console.log调用的每个组件执行以下操作,则输出将类似于以下内容:

view // your view object which contains methods and properties - BackboneView
render  // a method of the view object - a function
el // a property of the view object - an HTMLElement

所以你不能调用el,因为它只是一个属性实际上它是一个HTMLElement对象。在你的代码中你是returning html。如果你通过view.render链接调用().el您必须使用this关键字返回示例。当您返回instance时,您可以访问所有instance '所以,当你返回html时,你不能链接视图对象,这就是为什么在演示中,它们返回this

render: function () {
    this.$el.html( this.template( this.model.toJSON() ));
    return this; // return the instance
}

无论如何,你都不应该返回视图的html,你总是想通过el$el属性来访问Backbone的html。

zfycwa2u

zfycwa2u2#

el不是函数,而是构成视图的HTML。调用render()通常会生成HTML并将其存储在el属性中。按照约定,此方法应返回this,以允许您直接引用对象(并用于链接)。
因此,view.render().el将呈现该元素并返回适合附加到DOM的HTML。

相关问题