[英]uncaught TypeError: Cannot call method 'replace' of undefined backbone.js
[英]TypeError: Cannot call method 'replace' of null - Backbone.js
我正在嘗試使用peepcode做一個教程骨干項目,但是我被卡住了。
我試圖通過從集合中創建一個新視圖來呈現來自控制台的視圖。 這是我的代碼
(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 })
在控制台中,我得到以下響應:
TypeError:無法調用null的方法“替換”
誰能幫我嗎?
庫視圖的元素很可能在您的標記中不存在。
這應該是真的
$('#library-template').length == 1;
如果您這樣做,則會發生此錯誤:
_.template(null)
_.template(undefined);
在不存在的元素上調用.html()
會返回undefined
。
library
變量(您用作LibraryView
的構造函數參數中的LibraryView
) LibraryView
設置為什么? 它不是全局定義的,因此可能為null
。 您需要首先聲明該變量:
var library = new Albums(),
libraryView = new LibraryView({ collection: library })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.