2012-12-16 45 views
0

我(作爲一個初學者)賺取微薄的骨幹功能追加我的鏈接,爲了這個,我使用的是集合被分配模式,Backbone.js的聚集拋出錯誤

但集合拋出錯誤..任何人都可以糾正我的代碼嗎?

$(function(){ 
    var Model = new Backbone.Model({ 
     data:[ 
       {name:'Yahoo',href:'http://www.yahoo.com'}, 
       {name:'Gmail',href:'http://www.gmail.com'}, 
       {name:'Bing',href:'http://www.bing.com'} 
       ]  
    }); 

    var Collection = new Backbone.Collection.extend({ 
     model:Model // is this not correct way to do? 
    }); 

    var View = Backbone.View.extend({ 
     el:'#container', 
     events:{ 
      'click button':'render' 
      }, 
     initialize:function(){ 
      this.collection = new Collection(); //throw the error! 
      this.template = $('#temp').children(); 
     }, 
     render:function(){ 
      var data = this.collection.get('data'); 
      for(i=0;i<data.length;i++){ 
       var li = this.template.clone().find('a') 
       .attr('href',data[i].href) 
       .text(data[i].name).end(); 
       this.$el.find('ul').append(li); 
      } 
     } 
    }); 

    var myLink = new View(); 

}) 

回答

2

模型用於存儲和管理單個數據塊。在你的情況下,這將是一個單一的名稱/ href對。通常你用Backbone.Model.extend創建模型「類」與您的所有特定模型的方法和屬性,然後您創建模型的實例與new或設置模型「類」作爲一個集合的model property以便收集,可以創建新的實例該模型。

你的模型應該看起來更像是這樣的:

var Model = Backbone.Model.extend({ 
    defaults: { 
     name: '', 
     href: '' 
    } 
}); 

注意,那裏面有沒有new,我們要做的僅僅是「類」立足於我們的模型實例。然後我們掛鉤型號最多的集合(再次使用extend沒有new):

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

現在,您可以create an instance of the collection,並把它的數據,對模型的數組:

var links = new Collection([ 
    { name: 'Yahoo', href: 'http://www.yahoo.com' }, 
    { name: 'Gmail', href: 'http://www.gmail.com' }, 
    { name: 'Bing', href: 'http://www.bing.com' } 
]); 

你經常將集合傳遞給視圖,而不是使視圖實例化集合; Backbone will automatically設置this.collection如果你說new SomeView({ collection: some_collection }),因此您可以:

var View = Backbone.View.extend({ 
    //... 
    initialize: function() { 
     this.template = $('#temp').children(); 
    }, 

new View({ collection: links })並通過this.collection訪問集合其他地方的視圖。

集合就是幾款機型的集合(有點像數組),這將有various useful Underscore methods mixed in這樣你就可以通過收集這樣的循環:

render: function() { 
    this.collection.each(function(link) { 
     var li = this.template.clone().find('a').attr('href', link.get('href')).text(link.get('name')); 
     this.$('ul').append(li); 
    }, this); 
} 

還要注意使用get訪問模型屬性,模型屬性和對象屬性是不同的東西。您也可以使用toJSON一次性平整所有數據。最後this參數each使得this回調內部的看法。骨幹已經在視圖的this.$()方法中提供了一個this.$el.find()別名,因此我也切換到了該方法。

下面是一個簡化的演示:http://jsfiddle.net/ambiguous/WSqLM/

+0

非常感謝你。這不僅僅是一個答案,也是提升自我的一個很好的解釋。再次感謝! – 3gwebtrain