[英]Uncaught TypeError: Cannot call method 'on' of undefined - Backbone.js
[英]Having trouble rendering backbone.js collection view. Getting “Uncaught TypeError: Cannot call method 'on' of undefined” in my initialize function
我剛好接觸過ebones.js,並且無法確定為什么我的視圖在coupons.js的第67行未定義。 我發布了要點,因為它們是很長的文件。
另外,如果我多次刷新瀏覽器,最終它會正常工作,然后我再次刷新,它會崩潰,並且我可以再次刷新直到它正常工作,然后再次刷新直到它崩潰。 痛苦的循環。
當您嘗試在null / undefined對象上調用方法時,會發生此錯誤。 問題在於,您為offerList
獲取數據的offerList
是異步的,但是您正在同步實例化集合視圖。 也就是說,這在CouponCollectionView
的構造函數中:
this.collection.on('add remove', this.render, this);
在集合仍為null時被調用:
var coupons = null;
$.getJSON('http://localhost:3000/api/coupons.json', function(response){
coupons = new CouponCollection(response);
app.coupons = coupons;
});
您可能要考慮使用var coupons = new CouponCollection()
並調用coupons.fetch()
-這樣,將立即實例化該集合,並准備在View中on
調用。
設置集合,以便您可以調用fetch
:
var CouponCollection = Backbone.Collection.extend({
model: Coupon,
// tell Backbone where to send the "fetch" request
url: 'http://localhost:3000/api/coupons.json'
});
立即實例化采集和呼叫fetch
就可以了:
var coupons = new CouponCollection();
coupons.fetch();
將一個reset
偵聽器添加到集合中(完成fetch
時觸發),並在處理程序中呈現視圖:
this.couponCollectionView = new app.CouponCollectionView({collection: this.couponList});
var self = this;
this.couponList.on("reset", function() {
$('#content').empty().append(self.couponCollectionView.render().el);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.