2012-07-23 73 views
1

我需要迭代骨幹集合並獲取從集合中的模型派生的對象數組。在骨幹模型中定義公共方法

的問題是,我不知道如何讓收集訪問創建對象內部的模型定義中給出當定義一個方法:Backbone.Model.extend({})

這是建築的例子,我有這麼遠:

// THE MODEL 
var TheModel = Backbone.Model.extend({ 
    // THE FOLLOWING IS NOT AVAILABLE AS A METHOD OF THE MODEL: 
    //  This isn't the actual method, but I though it might be helpful to 
    //  to demonstrate that kind of thing the method needs to do (manipulate: 
    //  map data and make it available to an external library) 
    get_derived_object: function(){ 
     return this.get('lat') + '_' this.get('lon'); 
    } 

}); 

// THE COLLECTION: 
var TheCollection = Backbone.Collection.extend({ 
    // Use the underscore library to iterate through the list of 
    //  models in the collection and get a list the objects returned from 
    //  the "get_derived_object()" method of each model: 
    get_list_of_derived_model_data: function(){ 
     return _.map(
      this.models, 
      function(theModel){ 
       // This method is undefined here, but this is where I would expect 
       //  it to be: 
       return theModel.get_derived_object(); 

      } 
     ); 
    } 

}); 

我不知道我要去的地方錯在這裏,但我有一些猜測: *收集不遍歷它的模型的方式,它應該 *公共方法不能在Bac中定義kbone.Model.extend({}) *我找錯了地方*從Backbone.js的是如何打算的誤解得到的其他一些建築的錯誤使用

的公共方法 任何幫助表示讚賞, 非常感謝!

編輯

的問題是,居然有在這個代碼中的bug。當集合被填充時,它沒有引用「TheModel」作爲它的模型類型,所以它創建了它自己的模型。

當定義集合添加的需要這行代碼:model: TheModel

var theCollection = Backbone.Collection.extend({ 
    model: TheModel, 
    ... 
}); 

回答

2

而不是使用:

return _.map(
    this.models, 
    function(theModel){ 
     // This method is undefined here, but this is where I would expect 
     //  it to be: 
     return theModel.get_derived_object(); 
    } 
); 

爲什麼不使用內置集合版本:

return this.map(function(theModel){ 
    return theModel.get_derived_object(); 
}); 

不知道這是否有幫助,但它值得一試。

並且爲了記錄,在new Backbone.Model(的第一個參數中定義的所有方法都是「公開」的,所以您已經掌握了基本知識。

+0

太棒了,這絕對是我應該做的,而不是直接使用下劃線庫,非常感謝! – 2012-07-23 19:42:11