2013-04-02 2 views
0

나는 backbone.js로 놀고있어 교착 상태에 빠졌습니다. 크롬 개발자 도구에서 콘솔의 텍스트 버전, 그래서 여기에숨겨진 Backbone.js 모델

window.Car = Backbone.Model.extend(); 
window.CarCollection = Backbone.Collection.extend({ 
    model: Car, 
    url:"../api/car/", 

}); 

window.CarListView = Backbone.View.extend({ 
    tagName:'ul', 

    initialize: function() { 
     this.model.on("reset", this.render); 
    }, 

    render: function (eventName) { 
     console.log(this.model);  //is an object 
     console.log(this.model.models); //is an empty array 

     return this; 
    }, 
}); 

// Router 
var AppRouter = Backbone.Router.extend({ 

    routes:{ 
     "":"list", 
     "cars/:id":"carDetails" 
    }, 

    list:function() { 
     this.carList = new CarCollection(); 
     this.carListView = new CarListView({model:this.carList}); 
     this.carList.fetch(); 
     $('#sidebar').html(this.carListView.render().el); 
    }, 

}); 

$(function() { 
    app = new AppRouter(); 
    Backbone.history.start(); 
}); 

나는 이미지를 게시 할 수있는 충분한 명성을하지 않아도된다 :

V r {length: 0, models: Array[0], _byId: Object, _events: Object, constructor: function…} 
    > _byId: Object 
    > _events: Object 
    > length: 4 
    > models: Array[4] 
    > __proto__: s 

내 문제는 내가 오전 여기 내 코드입니다 비어있는 모델 뒤에 숨겨진 것으로 보이는 비어 있지 않은 모델 속성에 액세스하려고합니다. 길이가 4 인 모델 속성에 어떻게 액세스합니까?

답변

1

이것은 콘솔 버릇이지만 여기 핵심 문제는 일반적입니다. .fetch() (비동기로드)을 호출 한 다음 데이터가로드 될 것으로 예상되는 즉시 .render()을 호출하고 있습니다. 당신은 당신이 그것을 액세스하기 전에 데이터가로드 될 때까지 기다릴 필요 -이 작업을 수행하는 방법에는 여러 가지가 있지만, 가장 쉬운 방법은 success 콜백 fetch에 전달하는 아마이 이상한 경우 때문에

var carListView = this.carListView; 
this.carList.fetch({ 
    success: function() { 
      $('#sidebar').html(carListView.render().el); 
    } 
}); 

콘솔 로그를 컬렉션이 아직로드되지 않았을 때 (Array[0] 표시) console.log으로 전화를 걸었지만로드가 완료되면 수동으로 검사합니다 (Array[4] 표시).

+0

감사 : 두 가지 : 1 : 해당 코드는 'Uncaught ReferenceError : carListView가 정의되지 않음'으로 표시됩니다. 2 : 'reset'이벤트에 대한 바인딩은 데이터를 가져온 후에 렌더링 함수를 호출하게 만들 것이라고 생각 했습니까? –

+1

1. 아 ~, 맞아. 편집해라. 'this' 참조가 콜백에서 작동하지 않으므로 뷰를 변수로 별칭 지정해야합니다. 2.'reset' 리스너가 작동해야하지만'.fetch()'를 호출 한 직후에 명시 적으로'carListView.render()'를 명시 적으로 호출하고 있습니다. – nrabinowitz