是否可以调用initialize()来初始化视图?

时间:2014-07-20 05:12:57

标签: backbone.js

在我的Backbone应用程序中,我有以下

  playlistView = new PlaylistView({ model: Playlist });
  Playlist.getNewSongs(function() {
    playlistView.initialize();
  }, genre, numSongs);
当某个ajax请求完成时,回调

Playlist.getNewSongs()。我想重新初始化视图。但是,我相信我这样做的方式导致这个problem视图两次听同一事件。是否可以接受这样的initialize()?如果没有,我该怎么做呢?

更新

我在Backbone中写了这个chrome extension来学习Backbone,目前它正处于一个设计地狱中。我正在重构整个代码库。下面的代码段是我的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');
      });

    },

1 个答案:

答案 0 :(得分: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中的逻辑完全不同,请加入其中。也许有一个更好的地方。