为什么视图不使用 .el 呈现

Why would views not render with .el?

本文关键字:el 呈现 视图 为什么      更新时间:2023-09-26

我终于有了我的Rails Todo List应用程序,可以使用Backbone的渲染器显示Todos。不过我有一个小问题。在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);
    }
});
});

如果要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。

el

是一个函数,而是构成视图的HTML。调用render()通常会生成 HTML 并将其存储在 el 属性中。按照约定,此方法应返回this允许您直接引用对象(以及用于链接)。

因此,view.render().el将呈现元素并返回适合追加到 DOM 的 HTML。