我是backbone.js 的新手,无法准确指出为什么我的 View 在 coupons.js 第 67 行上未定义。我发布了一个要点,因为它们是相当长的文件。
另外,如果我刷新浏览器很多次,最终它工作得很好,然后我再次刷新它就会中断,我可以再次刷新直到它工作,然后再次刷新直到它中断。痛苦的循环。
最佳答案
当您尝试调用空/ undefined object 的方法时,会发生此错误。问题是您为 offerList
获取数据的调用是异步的,但您正在同步实例化 Collection View 。也就是说,在 CouponCollectionView
的构造函数中:
this.collection.on('add remove', this.render, this);
在集合仍为空时被调用:
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
完成时触发),并在处理程序中渲染 View :
this.couponCollectionView = new app.CouponCollectionView({collection: this.couponList});
var self = this;
this.couponList.on("reset", function() {
$('#content').empty().append(self.couponCollectionView.render().el);
});
关于javascript - 渲染backbone.js Collection View 时遇到问题。在我的初始化函数中获取“未定义”的 "Uncaught TypeError: Cannot call method ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13794279/