2013-05-11 51 views
0

我想用peepcode做一個教程骨幹項目,但我被卡住了。TypeError:無法調用方法'替換'空 - Backbone.js

我想通過從集合中創建一個新視圖來從控制檯呈現視圖。這裏是我的代碼

(function($) { 

    window.Album = Backbone.Model.extend({ 

     isFirstTrack: function(index) { 
      return index == 0; 
     }, 

     isLastTrack: function(index) { 
      return index >= this.get('tracks').length - 1; 
     }, 

     trackUrlAtIndex: function(index) { 
      if (this.get('tracks').length >= index) { 
       return this.get('tracks')[index].url; 
      } 
      return null; 
     } 

    }); 

    window.Albums = Backbone.Collection.extend({ 
     model: Album, 
     url: '/albums' 
    }); 

    window.Album = Backbone.Model.extend({}); 

    window.AlbumView = Backbone.View.extend({ 
     tagName: 'li', 
     className: 'album', 


     initialize: function() { 
      _.bindAll(this, 'render'); 
      this.model.bind('change', this.render); 

      this.template = _.template($('#album-template').html()); 
     }, 

     render: function() { 
      var renderedContent = this.template(this.model.toJSON()); 
      $(this.el).html(renderedContent); 
      return this; 
     } 
    }); 

    window.LibraryAlbumView = AlbumView.extend({ 

    }); 

    window.LibraryView = Backbone.View.extend({ 
     tagName: 'section', 
     className: 'library', 

     initialize: function() { 
      _.bindAll(this, 'render'); 
      this.template = _.template($('#library-template').html()); 
      this.collection.bind('reset', this.render); 
     }, 

     render: function() { 
      var $albums, 
       collection = this.collection; 

      $(this.el).html(this.template({})); 
      $albums = this.$(".albums"); 
      collection.each(function(album) { 
       var view = new LibraryAlbumView({ 
        model: album, 
        collection: collection 
       }); 
       $albums.append(view.render().el); 
      }); 
      return this; 
     } 
    }); 
})(jQuery); 

當我鍵入libraryView = new LibraryView({ collection: library }) 在控制檯中我得到這樣的迴應:

類型錯誤:無法調用空的「替換」

任何人都可以幫我嗎?

+0

您需要深入一點。嘗試在LibraryView中註釋單個行,直到錯誤消失。一旦你確定了確切的線路導致錯誤,你可以很容易地解決它。或者如果您熟悉這一點,請使用調試器。 http://www.youtube.com/watch?v=c_oiQYirKuY – 2013-05-11 20:37:55

回答

2

很可能庫視圖的元素不存在於您的標記中。

這應該是真實的

$('#library-template').length == 1; 

如果你這樣做可能發生此錯誤:

_.template(null) 
_.template(undefined); 

不存在收益undefined一個元素上調用.html()

+0

感謝兄弟!愚蠢的錯誤在我身上.... – Mike 2013-05-11 21:32:27

1

library變量(您用作LibraryView的構造函數參數中的值)的設置是什麼?它沒有全球定義,所以它可能是null。您需要首先聲明該變量:

var library = new Albums(), 
    libraryView = new LibraryView({ collection: library }) 
相關問題