我有一个用户列表来自parse.com的抓取并由view呈现。一旦人们点击项目列表,我会在url中插入objectid。在路由器中我创建了一个函数“home”,它从集合和调用视图中获取渲染。函数“userdetails”捕获objectid以前在url中的视图插入并使用它来从集合中获取。问题是:如何将集合传递给此函数userdetails?我不想再进行另一次获取。
home: function() {
var self=this;
console.log("inrouterhome");
var utenti = new Usercollection();
utenti.fetch({
success: function(object) {
var page=new Homelistuser({model:object});
self.changePage(page);
},
error: function(amici, error) {
// The collection could not be retrieved.
}
});
},
userDetails: function (objectId) {
HERE I WANNA USE OBJECTID TO MAKE A GET FROM COLLECTION FETCHED IN HOME
},
答案 0 :(得分:0)
看起来这可能是一个范围问题。试试这个
var Models = {};
var AppRouter = Backbone.Router.extend({
home: function() {
var self=this;
console.log("inrouterhome");
Models.utenti = new Usercollection();
Models.utenti.fetch({
success: function(object) {
var page=new Homelistuser({model:object});
self.changePage(page);
},
error: function(amici, error) {
// The collection could not be retrieved.
}
});
},
userDetails: function (objectId) {
//Models.utenti should exist as long as home came first,
// may want to write a condition that check to see if it exists and if not do fetch.
}
});
答案 1 :(得分:0)
正如@abritez所提到的,这可能是一个范围问题,即userDetails方法无法访问实例化的集合。 @ abritez的解决方案可解决此问题,但如果用户刷新页面或直接访问路径,则不会加载该集合。
如果在两个路由之间使用集合,请考虑在运行时获取它并在准备就绪时使用侦听器:
var Models = {};
Models.utenti = new Usercollection();
Models.utenti.fetch();
var AppRouter = Backbone.Router.extend({
home: function() {
var utentiLoaded = function(object) {
var page = new Homelistuser({model:object});
this.changePage(page);
}
this.listenTo(Models.utenti, 'reset', utentiLoaded);
this.listenTo(Models.utenti, 'error', function(amici, error) {
// The collection could not be retrieved.
});
if (Models.utenti.any()) {
utentiLoaded(Models.utenti);
}
},
userDetails: function(objectId) {
var utentiLoaded = function(object) {
}
this.listenTo(Models.utenti, 'reset', utentiLoaded);
this.listenTo(Models.utenti, 'error', function(amici, error) {
// The collection could not be retrieved.
});
if (Models.utenti.any()) {
utentiLoaded(Models.utenti);
}
}
});