假设我有一个名为 index 的主干路由,它从服务器获取集合:
var characters = new App.Collections.Characters();
characters.fetch({
success: function(data) {
var homeView = new App.Views.Home({
collection: new Backbone.Collection(data)
});
$('#content').html(homeView.render().el);
}
});
很简单吧?获取成功后,创建一个新 View 并用从服务器检索的数据填充它。
这假设我只传递一个字符数组。在 Express 3.0 中:
res.send(characters.slice(counter, counter+2)); // array of 2 characters
现在,如果我要包含 nonce除了这两个字符之外,还传递一个对象:
res.send({ nonce: randomString, characters: characters.slice(counter, counter+2);
当我这样做时,我无法再访问字符或随机数:
// the same fetch function from above
success: function(data) {
console.log(data.nonce); // undefined
console.log(data.characters); // undefined
}
Backbone Collection 是否在幕后做着什么见不得人的事情?为什么我无法从服务器传递的集合获取的成功对象访问我的对象属性?
更新:
以下是当我将一个简单数组发送到我的集合时的控制台输出,如第一种情况所示:
当我按照 @matt2000 的建议发送数据,然后在 Backbone 中将其调用为 data.models[0].attributes.characters;
:
最佳答案
Backbone 在底层发挥了一些魔力。将作为第一个参数传递给 success
回调的不是服务器提供的原始数据,而是解析后的集合 ( Backbone doc )。
您可以重写集合的默认 parse
方法,以便从服务器的响应中获取数组。
var Characters = Backbone.Collection.extend({
url : //REST access point
parse : function( response ) {
this.nonce = response.nonce;
// Anything returned by this function will be used as the first argument to
// construct the collection.
return response.characters;
}
});
现在,您可以在获取时直接使用字符实例,而不必使用其结果创建新的集合。
var characters = new Characters();
characters.fetch({
success: function( collection ) {
var homeView = new App.Views.Home({
collection: collection
});
$('#content').html(homeView.render().el);
}
});
关于javascript - 将额外数据传递给 Backbone Collection fetch——返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17331112/