[英]Having trouble rendering backbone.js collection view. Getting “Uncaught TypeError: Cannot call method 'on' of undefined” in my initialize function
I am new to backbone.js and am having trouble pin pointing why my view is undefined on line 67 of coupons.js. 我刚好接触过ebones.js,并且无法确定为什么我的视图在coupons.js的第67行未定义。 I posted a gist as they are pretty long files. 我发布了要点,因为它们是很长的文件。
Also, if I refresh the browser a bunch of times, eventually it works just fine and then I refresh again and it breaks and I can refresh again until it works and then again until it breaks. 另外,如果我多次刷新浏览器,最终它会正常工作,然后我再次刷新,它会崩溃,并且我可以再次刷新直到它正常工作,然后再次刷新直到它崩溃。 Painful cycle. 痛苦的循环。
This error occurs when you try to call a method on an object that's null/undefined. 当您尝试在null / undefined对象上调用方法时,会发生此错误。 The issue is that your call to fetch data for offerList
is asynchronous, but you're instantiating the collection view synchronously. 问题在于,您为offerList
获取数据的offerList
是异步的,但是您正在同步实例化集合视图。 That is, this in CouponCollectionView
's constructor : 也就是说,这在CouponCollectionView
的构造函数中:
this.collection.on('add remove', this.render, this);
is getting called while the collection is still null: 在集合仍为null时被调用:
var coupons = null;
$.getJSON('http://localhost:3000/api/coupons.json', function(response){
coupons = new CouponCollection(response);
app.coupons = coupons;
});
You might want to consider using var coupons = new CouponCollection()
, and calling coupons.fetch()
-- that way, the collection will be instantiated immediately, and ready for your on
call in the View. 您可能要考虑使用var coupons = new CouponCollection()
并调用coupons.fetch()
-这样,将立即实例化该集合,并准备在View中on
调用。
Set up the collection so that you can call fetch
: 设置集合,以便您可以调用fetch
:
var CouponCollection = Backbone.Collection.extend({
model: Coupon,
// tell Backbone where to send the "fetch" request
url: 'http://localhost:3000/api/coupons.json'
});
Instantiate the collection immediately, and call fetch
on it: 立即实例化采集和呼叫fetch
就可以了:
var coupons = new CouponCollection();
coupons.fetch();
Add a reset
listener to the collection (triggers when fetch
is complete), and render the view in the handler: 将一个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.