내가 컬렉션을 가지고 있고 경로가 발사 될 때 내가 컬렉션에 모델에 액세스해야합니다백본 라우터 및 수집 문제
App.Houses = Backbone.Collection.extend({
model: App.House,
url: API_URL,
})
App.houseCollection = new App.Houses()
App.houseCollection.fetch();
App.HouseDetailRouter = Backbone.Router.extend({
routes: {
'': 'main',
'details/:id': 'details',
},
initialize: function() {
},
main: function() {
App.Events.trigger('show_main_view');
},
details: function(id) {
model = App.houseCollection.get(id);
console.log(model);
App.Events.trigger('show_house', model);
},
});
console.log(model)
이 undefined
입니다의 결과입니다. 컬렉션이 fetch()
호출을 완료하지 않았기 때문에 이것이 사실이라고 생각하십니까?
이벤트에 응답하는보기가 활용할 수 있도록 모델을 내가 실행중인 이벤트에 첨부하려고합니다. 나는 나쁜 접근법을 취하고 있을지도 모르겠다. 이벤트에 응답하는 뷰의
하나 :
App.HouseDetailView = Backbone.View.extend({
el: '.house-details-area',
initialize: function() {
this.template = _.template($('#house-details-template').html());
App.Events.on('show_house', this.render, this);
App.Events.on('show_main_view', this.hide, this);
},
events: {
'click .btn-close': 'hide',
},
render: function(model) {
var html = this.template({model:model.toJSON()});
$(this.el).html(html);
$(this.el).show();
},
hide: function() {
$(this.el).hide();
App.detailsRouter.navigate('/', true);
}
});
편집 : 다소 해키 수정 : 당신이 콜백이나 이벤트도를 사용하고 있기 때문에 세부 사항()
App.HouseDetailRouter = Backbone.Router.extend({
routes: {
'': 'main',
'details/:id': 'details',
},
initialize: function() {
},
main: function() {
App.Events.trigger('show_main_view');
},
details: function(id) {
if (App.houseCollection.models.length === 0) {
// if we are browsing to website.com/#details/:id
// directly, and the collection has not finished fetch(),
// we fetch the model.
model = new App.House();
model.id = id;
model.fetch({
success: function(data) {
App.Events.trigger('show_house', data);
}
});
} else {
// if we are getting to website.com/#details after browsing
// to website.com, the collection is already populated.
model = App.houseCollection.get(id);
App.Events.trigger('show_house', model);
}
},
});
컬렉션에 'id'가있는 모델이 있는지 확인 하시겠습니까? 당신은'console.log (App.houseCollection.models)'을 볼 수 있습니다. –
'console.log를 호출 할 때 (App.houseCollection.models')'[]'이 있습니다. – AlexBrand
필요에 따라 컬렉션을 가져 왔습니까? –