2012-06-15 4 views
1

내가 컬렉션을 가지고 있고 경로가 발사 될 때 내가 컬렉션에 모델에 액세스해야합니다백본 라우터 및 수집 문제

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); 
     } 
    }, 
}); 
+0

컬렉션에 'id'가있는 모델이 있는지 확인 하시겠습니까? 당신은'console.log (App.houseCollection.models)'을 볼 수 있습니다. –

+0

'console.log를 호출 할 때 (App.houseCollection.models')'[]'이 있습니다. – AlexBrand

+0

필요에 따라 컬렉션을 가져 왔습니까? –

답변

1

를 참조하십시오 컬렉션의 fetch 호출이 완료되면 컬렉션을 가져 오면 오류가 발생하거나 원하는 모델이 서버 응답에 포함되지 않았거나 이전에보기로 라우팅 중일 때를 알 수 있습니다. fetch가 완료되었습니다.

당신의 접근 방식에 관해서는, 여기에 몇 가지 기타 팁은 다음과 같습니다

  • 더 나은 뷰의 생성자의 options 매개 변수의보기로 모델을 통과 할 수 있습니다. render()은 아무런 논점도 가지고 있지 않으며, 나는 그것을 바꾸는 것이 비 전통적이라고 생각합니다.
  • 항상 당신이 extend에 전달 객체 리터럴에 this.template = _.template 코드를 이동할 수 있습니다 귀하의 의견
  • render()에서 this을 반환합니다. 이 코드는 각 개별보기가 아닌 앱로드 당 한 번만 실행하면됩니다.
  • 이제 가장 간단한 것은 details 경로 기능에서 모델과보기를 인스턴스화하는 것일 수 있습니다. 특정 모델에 fetch을 호출하고, 보기를 렌더링 할시기를 알기 위해 success 콜백을 사용하십시오.
+0

내 변경 사항을 추가했지만 꽤 해킹 된 것처럼 보입니다 ... 내 구조를 다시 생각해야 할 수도 있습니다. – AlexBrand

+0

이 생각이 들었습니다 ... 컬렉션이 main() 경로에서 인스턴스화되어야합니까? 라우터의 기능에 대해 너무 확신하지 못함 – AlexBrand

+0

'collection.get'을 사용하여 모델을 확인하십시오. 관심있는 항목에 대해 더 정확하기 때문에 길이를 확인하는 것보다 낫습니다. 거기 있건 없건간에. 모델이 반환되지 않으면 모델을 가져 와서 컬렉션에 추가하여 다음 번에 모델을 추가합니다. –