2014-07-20 1 views
0

, 나는 보기를 초기화하려면 initialize()를 호출해도 괜찮습니까? 일부 Ajax 요청이 완료되면 내 백본 응용 프로그램에서

playlistView = new PlaylistView({ model: Playlist }); 
    Playlist.getNewSongs(function() { 
    playlistView.initialize(); 
    }, genre, numSongs); 

Playlist.getNewSongs()

다음 한 것은 다시이라고합니다. 내가보기를 다시 초기화하고 싶습니다. 그러나, 나는 그것을하고있는 방법이 같은 이벤트를 두 번 듣는보기의 problem에 이르게한다고 믿습니다. initialize()을 이렇게 쓸 수 있습니까? 그렇지 않다면 대신 무엇을해야합니까?

업데이트 :

나는 백본을 배울 백본이 chrome extension을 쓴, 그리고 순간에 디자인 지옥에서입니다. 나는 전체 코드베이스를 리팩토링 중이다. 아래의 스 니펫은 PlaylistView initialize() 코드 블록입니다.

var PlaylistView = Backbone.View.extend({ 
    el: '#expanded-container', 

    initialize: function() { 
     var playlistModel = this.model; 
     var bg = chrome.extension.getBackgroundPage(); 

     if (!bg.player) { 
     console.log("aborting playlistView initialize because player isn't ready"); 
     return; 
     } 

     this.listenTo(playlistModel.get('songs'), 'add', function (song) { 
     var songView = new SongView({ model: song }); 
     this.$('.playlist-songs').prepend(songView.render().el); 
     }); 

     this.$('#song-search-form-group').empty(); 
     // Empty the current playlist and populate with newly loaded songs 
     this.$('.playlist-songs').empty(); 
     var songs = playlistModel.get('songs').models; 

     // Add a search form 
     var userLocale = chrome.i18n.getMessage("@@ui_locale"); 
     var inputEl = '<input class="form-control flat" id="song-search-form" type="search" placeholder="John Lennon Imagine">' + 
      '<a href="javascript:void(0)" id="open-favorites"><span class="search-heart-icon fa fa-heart"></span></a>'+ 
      '<span class="search-input-icon fui-search"></span>'; 
     } 
     this.$('#song-search-form-group').append(inputEl); 
     var form = this.$('input'); 
     $(form).keypress(function (e) { 
     if (e.charCode == 13) { 
      var query = form.val(); 
      playlistModel.lookUpAndAddSingleSong(query); 
     } 
     }); 

     // Fetch song models from bg.Songs's localStorage 
     // Pass in reset option to prevent fetch() from calling "add" event 
     // for every Song stored in localStorage 
     if (playlistModel.get('musicChart').source == "myself") { 
     playlistModel.get('songs').fetch({ reset: true }); 
     songs = playlistModel.get('songs').models; 
     } 

     // Create and render a song view for each song model in the collection 
     _.each(songs, function (song) { 
     var songView = new SongView({ model: song }); 
     this.$('.playlist-songs').append(songView.render().el); 
     }, this); 

     // Highlight the currently played song 
     var currentSong = playlistModel.get('currentSong'); 
     if (currentSong) 
     var currentVideoId = currentSong.get('videoId'); 
     else { 
     var firstSong = playlistModel.get('songs').at(0); 
     if (!firstSong) { 
      // FIXME: this should be done via triggering event and by Popup model 
      $('.music-info').text(chrome.i18n.getMessage("try_different_chart")); 
      $('.music-info').fadeOut(2000); 
      //console.log("something wrong with the chart"); 
      return; 
     } 
     var currentVideoId = firstSong.get('videoId'); 
     } 

     _.find($('.list-group-item'), function (item) { 
     if (item.id == currentVideoId) 
      return $(item).addClass('active'); 
     }); 

    }, 
+0

'초기화'와 같이 호출하는 것은 '정상'이 아닙니다. 손을 떼면, 초기화하는 데 너무 많은 노력을하는 것처럼 들립니다. – fbynite

답변

1

잘못된 것은 아니지만 좋은 사례는 아닙니다. initialize에 코드를 게시하지 않았지만 여기에 너무 많은 논리가있을 수 있습니다.

새로운 데이터가 렌더링되는, 당신과 같은 이벤트 리스너를 사용한다, 그래서 당신은 단순히 다시보기를 초기화하는 경우 :

myView = Backbone. View.extend ({ 
    initialize : function() { 
     // We bind the render method to the change event of the model. 
     //When the data of the model of the view changes, the method will be called. 
     this.model.bind("change" , this.render, this); 

     // Other init code that you only need once goes here ... 
     this.template = _.template (templateLoader. get('config')); 
    }, 

    // In the render method we update the view to represent the current model 
    render : function(eventName) {  
     $ (this.el).html(this .template ((this.model .toJSON())));  
     return this;   
    } 

}); 

당신의 initiialize의 논리는 완전히 다른 것 인 경우를 포함하십시오. 아마 더 좋은 장소가있을 것입니다.

+0

안녕하세요. 내 전체 PlaylistView를 업데이트했습니다. –

관련 문제