访问Backbone Collection属性时出现undefined的问题求助
解决Backbone Collection中header/stats属性undefined的问题
嘿,我一眼就瞅出问题所在啦——你遇到的header和stats返回undefined的情况,核心原因是Backbone的fetch是异步操作,你在调用fetch之后立刻去打印属性,这时候请求还没完成,parse函数都还没执行呢,自然拿不到值!
另外还要提个小细节:你代码里打印的是personCollection.status,但parse里赋值的是this.stats,这是个笔误,得修正哦。
下面给你两个靠谱的解决方案:
方案1:使用fetch的success回调
把需要访问属性的逻辑放在success回调里,这个回调会在请求成功、parse执行完成后触发:
var personCollection = new PersonCollection(); personCollection.fetch({ success: function(collection, response) { console.log(collection.header); // 正常输出header值 console.log(collection.stats); // 正常输出stats值(注意这里是stats不是status) } });
方案2:监听sync事件
Backbone的Collection在成功同步数据后会触发sync事件,我们可以监听这个事件来处理后续逻辑:
var personCollection = new PersonCollection(); // 先绑定事件,再发起请求 personCollection.on('sync', function() { console.log(this.header); console.log(this.stats); }); personCollection.fetch();
你的parse函数写法是没问题的,它会在请求返回后正确把resp.header和resp.stats挂载到Collection实例上,只要等异步操作完成后再访问这些属性就可以啦!
内容的提问来源于stack exchange,提问作者Nithin
相关产品推荐
相关产品推荐

