簡體   English   中英

呈現lobb.js集合視圖時遇到問題。 在我的初始化函數中得到“ Uncaught TypeError:無法調用未定義的方法'on'”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM