骨干转JSON
Posted
技术标签:
【中文标题】骨干转JSON【英文标题】:Backbone toJSON 【发布时间】:2012-08-24 02:40:33 【问题描述】:我要么非常累,要么真的很困惑……但我不确定……我有一个 parse.com javascript 设置(它与主干.js 完全一样,只是使用解析而不是主干)。我有一个模型和一个系列,这一切都有效。但是该死的 toJSON();不起作用,它只会在 console.log 中返回一个 []... 但是,如果我在 Chrome 控制台中运行相同的函数,它会起作用并返回正确的值。
有什么帮助吗!?
所有这些可爱的代码都包装在一个准备好的文档中(它还有一些其他不相关的代码,是的,我有 Parse.initialize()
'd 它。
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();我得到了正确的值......正如你所看到的,我已经试图解决这个问题(以防你想知道为什么一切都在这个地方)。还有一点需要注意的是,我使用的是 Zepto.js 而不是 jQuery。
谢谢!
【问题讨论】:
【参考方案1】:可能在您执行schedule.toJSON()
时它仍然是空的。
请记住,Collection.fetch()
是一个异步方法。
尝试修改这一行:
schedule.fetch();
通过这个:
schedule.fetch( success: function() console.log( "what about now?", schedule.toJSON() ) ;
(您可能会遇到 context 问题,尝试使 schedule
变量可访问到 success
处理程序)
【讨论】:
以上是关于骨干转JSON的主要内容,如果未能解决你的问题,请参考以下文章