2014-03-25 137 views
0

據我所知我可以渲染自己的el元素,我正在學習BackboneJS,使用一本名爲初始骨幹的書, 。然而,當我調用渲染功能時,它不會在頁面上呈現任何內容,當我使用console.log(view.el)時,它將不會渲染任何內容,即 ;它輸出應該呈現的內容,所以我猜它是渲染函數的一個問題。爲什麼我的視圖不能渲染?

var Book = Backbone.Model.extend({ 
    defaults: 
    { 
     title: "default title", 
     author: "default author", 
     pages: 0 
    } 
}); 

var Library = Backbone.Collection.extend({ 
    model: Book 
}); 

var View = Backbone.View.extend({ 
    initialize: function() 
    { 
     this.render(); 
    }, 
    render: function() 
    { 
     this.$el.html('Hello Library'); 
     return this;    
    } 
}); 

var book1 = new Book({title: "title1",author:"author1",pages: 11}); 
var book2 = new Book({title: "title2",author:"author2",pages: 2}); 

var library = new Library([book1,book2]); 

var view = new View({ 
    model: book1, 
    tagName: 'ul', 
    className: 'page', 
    attributes: {'data-date': new Date()} 
}); 

回答

2

試試這個:http://jsfiddle.net/tonicboy/nWvRy/

你有問題,你指定的標記和類名,這會使一個分離的節點。您必須手動將該節點附加到屏幕上的某個位置才能顯示。另一個選項(我已經完成)是爲屏幕上已有的元素指定一個el屬性,然後該視圖將呈現(附加)到該預先存在的節點。您可以使用eltagName,classNameattributes,但不能同時使用。

HTML:

<div id="view-wrapper"></div> 

JS:

var Book = Backbone.Model.extend({ 
    defaults: 
    { 
     title: "default title", 
     author: "default author", 
     pages: 0 
    } 
}); 

var Library = Backbone.Collection.extend({ 
    model: Book 
}); 

var View = Backbone.View.extend({ 
    initialize: function() 
    { 
     this.render(); 
    }, 
    render: function() 
    { 
     this.$el.html('Hello Library'); 
     return this;    
    } 
}); 

var book1 = new Book({title: "title1",author:"author1",pages: 11}); 
var book2 = new Book({title: "title2",author:"author2",pages: 2}); 

var library = new Library([book1,book2]); 

var view = new View({ 
    model: book1, 
    el: '#view-wrapper', 
    attributes: {'data-date': new Date()} 
}); 

UPDATE:

這裏是它採用tagNameclassNameattributes另一個版本。注意view render()方法必須將其附加到現有元素。

http://jsfiddle.net/tonicboy/nWvRy/1/

+0

我希望我能喜歡這個不止一次 – user254883

相關問題