我要么非常疲倦,要么真的很困惑......但我不确定......我有一个 parse.com javascript 设置(它与 backbone.js 完全一样,只是使用解析而不是主干)。我有一个模型和一个系列,一切正常。但是该死的 toJSON();不起作用,它只是在 console.log 中返回一个 []...但是,如果我在 Chromes 控制台中运行相同的函数,它会起作用并返回正确的值。
任何帮助!?
所有这些可爱的代码都包装在一个准备好的文档中(它还有一些其他不相关的代码,是的,我有 Parse.initialize()
了。
var Schedule = Parse.Object.extend({
className: "schedule"
});
var ScheduleList = Parse.Collection.extend({
model: Schedule
});
schedule = new ScheduleList();
schedulejs3 = schedule.toJSON();
schedule.query = new Parse.Query(Schedule);
schedule.query.ascending("date");
schedule.query.limit('500');
schedulejs2 = schedule.toJSON();
schedule.fetch();
schedulejs = schedule.toJSON();
console.log(schedulejs,schedulejs2,schedulejs3); <-- All three return []
var ScheduleView = Parse.View.extend({
el: $("#schedule-holder"),
initialize: function() {
this.schedule = new ScheduleList();
this.schedule.query = new Parse.Query(Schedule);
this.schedule.query.ascending("date");
this.schedule.query.limit('500');
this.schedule.fetch();
this.schedule.js = this.schedule.toJSON();
this.render;
},
render: function() {
var template = Handlebars.compile($("#schedule-item").html());
$(this.el).html(template({shows: this.schedule.toJSON()}));
return this;
}
});
var App = new ScheduleView().render();
但是如果我在 Chrome 中打开控制台并运行 schedule.toJSON();我得到了正确的值...如您所见,我有点破坏了我的 backbone.js 设置,试图弄清楚这一点(以防您想知道为什么一切都乱七八糟)。请注意,我使用的是 Zepto.js 而不是 jQuery。
谢谢!
最佳答案
可能在您执行 schedule.toJSON()
时它仍然是空的。
请记住,Collection.fetch()
是一种异步方法。
尝试修改这一行:
schedule.fetch();
由此:
schedule.fetch({ success: function() { console.log( "what about now?", schedule.toJSON() ) } };
(可能您会遇到一个上下文问题,尝试使schedule
变量可访问到success
处理程序中)
关于javascript - Backbone 到JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12178750/