2011-08-31 6 views
4

백본이 컬렉션에 지정된 모델을 사용하고 있지 않습니다. 나는 뭔가를 놓치고 있어야합니다.Backbone.js 컬렉션 모델 값이 사용되지 않습니다.

App.Models.Folder = Backbone.Model.extend({ 
    initialize: function() { 
    _.extend(this, Backbone.Events); 

    this.url = "/folders"; 
    this.items = new App.Collections.FolderItems(); 
    this.items.url = '/folders/' + this.id + '/items'; 
    }, 

    get_item: function(id) { 
    return this.items.get(id); 
    } 
}); 

App.Collections.FolderItems = Backbone.Collection.extend({ 
    model: App.Models.FolderItem 
}); 

App.Models.FolderItem = Backbone.Model.extend({ 
    initialize: function() { 
    console.log("FOLDER ITEM INIT"); 
    } 
}); 


var folder = new App.Models.Folder({id:id}) 
folder.fetch(); 

// later on change event in a view 
folder.items.fetch(); 

폴더가로드는 항목은 다음로드 있지만 호출되지 않습니다 개체 및 폴더 항목 INIT를 FolderItem되지 않습니다. 그것들은 기본 Model 객체입니다.

무엇을 놓쳤습니까? 나는 이것을 다르게해야 할까?

편집 : 왜 이것이 작동하는지는 잘 모르겠지만 다음과 같은 이유가 있습니다. 백본 5.3

App.Collections.FolderItems = Backbone.Collection.extend({ 
    model: function(attributes) { 
    return new App.Models.FolderItem(attributes); 
    } 
}); 

답변

7

문제는 모델과 컬렉션에 대한 선언 순서입니다. 기본적으로 모델을 먼저 정의해야합니다.

App.Models.FolderItem = Backbone.Model.extend({...}); 

App.Collections.FolderItems = Backbone.Collection.extend({ 
    model: App.Models.FolderItem 
}); 

이유는 백본 개체가 개체 리터럴 구문으로 정의된다는 것입니다. 즉, 정의시 즉시 평가됩니다.

이 코드는 동일한 기능이지만, 객체 리터럴 성격을 보여 folderItemDef 및 folderItems 데프가 key: value쌍이 정의를 즉시 평가가 모두 객체 리터럴이 있음을

var folderItemDef = { ... }; 

var folderItemsDef = { 
    model: App.Models.FolderItem 
} 

App.Models.FolderItem = Backbone.Model.extend(folderItemDef); 

App.Collections.FolderItems = Backbone.Collection.extend(folderItemsDef); 

당신이 예에서 볼 수 리터럴의.

원래 코드로 컬렉션을 먼저 정의했습니다. 이는 컬렉션이 정의 될 때 App.Models.FolderItem이 정의되지 않음을 의미합니다. 그래서 당신은 기본적으로이 일을하고 있습니다 :

App.Collection.extend({ 
    model: undefined 
}); 

컬렉션 정의 위의 모델 정의를 이동하여,하지만, 컬렉션 모델을 찾을 수있을 것입니다 그리고 그것은 제대로 연결됩니다.

FWIW : 컬렉션 모델을 설정하는 함수 버전이 작동하는 이유는 앱이 실행되고 모델이 컬렉션에로드 될 때까지 함수가 평가되지 않기 때문입니다. 이 시점에서 자바 스크립트 인터프리터는 이미 모델의 정의를 찾았고 올바르게로드합니다.

+0

아, 맞아. 감사! – Candland

+0

이것은 나를 잡았습니다. 그것은 매우 비밀스러운 오류를 일으켰습니다. 나는 이것을 문서에서 강조해야한다고 생각한다. – UpTheCreek

관련 문제