2012-06-21 45 views
0

我終於得到了我的Rails Todo List應用程序來顯示使用Backbone的渲染器的Todos。雖然我有一個小問題。在addOne函數中,我使用了view.render()而不是view.render()。el,本教程中教授的內容。爲什麼視圖不能用.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

如果你要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的屬性和方法(chainablility)。因此,當您返回html時,您無法鏈接視圖對象,這就是爲什麼在演示中返回this

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

無論如何你都不應該返回視圖的html。您總是希望通過el$el屬性訪問Backbone的html。

1

el不是一個函數,而是構成視圖的HTML。調用render()通常會生成HTML並將其存儲在el屬性中。按照慣例,這個方法應該返回this,允許你直接引用對象(和鏈接)。

因此,view.render().el將呈現該元素並返回適合附加到DOM的HTML。