我正在 Parse.com 中编写一个应用程序,我已经定义了一个“AppState”对象,它存储了我通过应用程序传递的各种常量和值(有点像 PHP session )。
有一次,我试图从 AppState 对象中读取一个值,虽然它似乎已设置,但我没有取回该值。
AppState 定义为:
var AppState = Parse.Object.extend("AppState", {
defaults: {
folderShown: '',
folderSpecial: 'all',
showCaption: false
}
});
然后我必须启动应用程序:
var state = new AppState;
new AppRouter;
new AppView;
在 AppRouter 中,我正在设置“route”的值:
var AppRouter = Parse.Router.extend({
routes: {
"viewPage/:object_id": "viewPage",
},
initialize: function(options) {
},
viewPage: function(object_id) {
state.set("currentPage", object_id);
state.set("route", "view");
}
});
在应用 View 中,我有:
var AppView = Parse.View.extend({
initialize: function() {
this.render();
},
render: function() {
console.log(state);
console.log(state.get('route'));
}
});
第一个控制台日志显示状态,属性“route”设置为“view”:
attributes: Object
folderShown: ""
folderSpecial: "all"
route: "view"
showCaption: false
第二个控制台日志显示“未定义”。
如果我获得默认属性之一,例如“folderSpecial”,它会读取正确的值。
我做错了什么?
最佳答案
在调用 Backbone.history.start()
时,会评估路由器中定义的路由。
来自 http://backbonejs.org/#Router
During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), or Backbone.history.start({pushState: true}) to route the initial URL.
这意味着您的状态对象只会在 Backbone.history.start()
被调用时更新:在您的情况下,在您的 View 初始化之后。
在 new AppView
之前调用 Backbone.history.start
应该可以解决您的问题。
Fiddle 模拟您的问题:http://jsfiddle.net/nikoshr/LWh2P/ 和修改版本:http://jsfiddle.net/nikoshr/LWh2P/1/
关于javascript - 无法在 Parse.com 中获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12492256/