2012-07-23 4 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 의도 방법에 대한 오해에서 파생 된 다른 어떤 건축 실수

을 사용하는 * public 메소드 에 대한 잘못된 장소에서 찾고 있어요 * 어떤 도움에 감사드립니다 , 정말 고마워!

편집

문제는 실제로이 코드에 버그가 있다고했다. 컬렉션에 데이터가 채워지면 모델 모델로 "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

굉장히, 바로 밑줄 라이브러리를 사용하는 대신에해야 할 일입니다. 정말 고마워요! –

관련 문제