2012-06-27 5 views
2

사용자가 http://example.com/#/playlist으로 이동하면 일부 노래를 나열하려고합니다.백본 직접 URL 액세스가 모음을 깨뜨림

처음에 http://example.com으로 이동하여 <a href="#/playlist">Playlist</a> 링크를 클릭하면 (모든 노래가 나열됩니다) 작동합니다.

그러나 직접 http://example.com/#/playlist으로 가면 아무 것도 표시되지 않습니다.

this.collection 속성을 기록하면 컬렉션이 항상 동일합니다 (링크를 사용하거나 직접 액세스하는 경우).

유일한 차이점은 아래의 렌더링 기능에서 this.collection.each(function (song) {});이며 URL에 직접 액세스 할 때 루프되지 않습니다.

define(
    [ 
     'jQuery', 
     'Underscore', 
     'Backbone', 
     'collections/songlist', 
     'views/song' 
    ], 

    function ($, _, Backbone, SonglistCollection, SongView) 
    { 
     var PlaylistView = Backbone.View.extend({ 

      // properties 
      el: '#content', 
      tagName: 'ul', 
      collection: new SonglistCollection(), 

      /** 
      * Initialize 
      */ 
      initialize: function() 
      { 
       // load songs 
       this.collection.bind('reset', this.render(), this); 
       this.collection.fetch(); 
      }, 

      /** 
      * Render 
      */ 
      render: function() 
      { 
       this.$el.html(''); 

       console.log(this.collection); 

       this.collection.each(function (song) 
       { 
        var songItem = new SongView({ model: song }); 
        this.$el.append(songItem.el); 

       }, this); 
      } 

     }); 

     return new PlaylistView; 

    } 
); 

이 문제는에서, 여기에 '각 루프'을 발생합니다 :

render: function() 
       { 
        this.$el.html(''); 

        console.log(this.collection); 

        this.collection.each(function (song) 
        { 
         var songItem = new SongView({ model: song }); 
         this.$el.append(songItem.el); 

        }, this); 
       } 

UPDATE이 내 라우팅 코드

코드입니다 :

define([ 
    'jQuery', 
    'Underscore', 
    'Backbone', 
    'views/start', 
    'views/playlist' 
], 

    function ($, _, Backbone, startView, playlistView) 
    { 
     var AppRouter = Backbone.Router.extend({ 
      routes: { 
       'playlist': 'playlist', 

       // default 
       '*actions': 'start' 
      }, 

      start: function() 
      { 
       // call render on the module we loaded via the dependency array 
       // views/items/list 
       startView.render(); 
      }, 

      playlist: function() 
      { 
       playlistView.render(); 
      }, 

      defaultAction: function (actions) 
      { 
       // no default action, let's just log what the url was 
       console.log('No route:', actions) 
      } 
     }); 

     var initialize = function() 
     { 
      var app_router = new AppRouter; 
      Backbone.history.start(); 
     } 

     return { 
      initialize: initialize 
     }; 
    } 

); 
+1

라우팅 코드를 추가 할 수 있습니까? – codemonkey

+0

라우팅 코드를 사용하여 게시물을 수정했습니다. 미리 감사드립니다. – Voles

+0

밑줄로 각 방법을 사용하고 있습니까? 나는 그것이'_.each (this.collection.models, function (sont) {// code}, this); ' – Jack

답변

0

을 초기화 한 후 require.js으로 반환하는 것이 문제라고 생각합니다. 또한 콜렉션이 확실히 페치를하기 전에 PlaylistView의 render 메소드를 임의적으로 호출합니다.

  1. 그래서 당신이 http://example.com을 통해 갈 때 :
    1. 이 playListView init을 필요
    2. startView
    3. init이 필요 -> 수집은 이제 채워 -> 컬렉션을 가져
    4. playListView가 수익을 가져 startView에
    5. 경로를 시작
    6. 링크 클릭 -> playListView 올바르게 렌더링
  2. 하고 http://example.com/#/playlist을 통해 갈 때 :
    1. 이 playListView init을 필요
    2. startView
    3. init이 필요 -> 컬렉션을 가져 playListView에
    4. 길을 시작 - 컬렉션 여전히 가져 오는 때문에> playListView을 렌더링하는 것은 잘못 (일명 아무것도 루프 없음)
    5. playListView가 수익을 가져 오기 -> 수집은 이제

C를 채워 필요한 무언가가 아직 언로드 왼쪽 동안 hange이 줄 return new PlaylistView;return PlaylistView;

에 그리고 물론 Router뿐만 아니라

function ($, _, Backbone, startView, **PlaylistView**) // change the variable name 
... 
var AppRouter = Backbone.Router.extend({ 
    ... 
    playlistView: null, // Add attribute for the router 
    ... 
    playlist: function() { 
    playlistView = new PlayListView(); 
    // No render because you bound the render to the reset of the collection !!! 
    }, 
    ... 
} 
... 

이제 당신은 초기화되지 않습니다 당신의 PlaylistView을 변경해야합니다.

+0

컬렉션이 업데이트되면 '렌더링'기능을 실행하는 것이 좋습니다. 감사! – Voles

1

나는 playlistView.render();Router에 호출 할 때 playlist.collection이 여전히 채워지지 않는다고 생각합니다.

당신은 console.log(this.collection);이 보여주는 것을 신뢰하고 있지만 복잡한 객체를 가진 console.log()을 신뢰할 수는 없습니다.

확인 : MVC 패턴에서

+0

기록 된 데이터가 실제로 올바르지 않습니다. 하지만 Jakee의 대답도 나를 도왔습니다. 한 aswer 확인 수 있지만 여전히 많이 감사합니다! – Voles

+0

upvoting도 고맙습니다 :) – fguillen

0

는, 뷰는 모델의 변화에 ​​반응한다.

this.collection.on('reset', this.render, this); 

그러나 문제는 다시보기를 다시 렌더링하는 원인이 리셋을 유발하지 않을 것입니다 : 당신은 당신의 코드에서 설정하는 것이 있습니다. 따라서 '재생 목록'에서 render 메소드를 호출하는 대신 콜렉션의 URL을 적절한 REST 엔드 포인트로 변경 한 다음 collection.fetch를 수행하십시오. 가져 오기를 수행하면 '재설정'이 실행되고 렌더링이 업데이트 된 컬렉션을 적절히 반영하여 호출됩니다.