我想知道是否可以通过以下方式将模型添加到集合中。我试过了,它不起作用。如果我直接添加JSON [],则可以。我知道这有点奇怪,但是我试图更好地了解BB的工作原理。谢谢。
var UserModel = Backbone.Model.extend({
urlRoot: '/users',
});
var UserModels = Backbone.Collection.extend({
url: '/users',
model: UserModel
});
var user = new UserModel({id:1});
user.fetch({ // get the model
success: function (user) {
var users = new UserModels();
users.add(user); // add the model to a collection
}
});
服务器正在回显以下模型:
[{"name":"john","email":"[email protected]"}]
由于服务器的响应是一个包含单个元素的数组,因此您需要添加一个解析函数,该函数返回该数组的第一个元素:
var UserModel = Backbone.Model.extend({
urlRoot: '/users',
parse: function(response){
if(response && response.length) return response[0];
}
});
这应该允许模型正确地解析服务器响应中的属性:[{"name":"john","email":"[email protected]"}]
。
顺便说一句,您将在成功功能中创建用户集合,因此该功能之外将无法使用它。它可能只是您发布的示例代码,但是您可以在外部创建users集合,只需在成功函数中添加模型:
var users = new UserModels();
var user = new UserModel({id:1});
user.fetch({ // get the model
success: function (user) {
users.add(user); // add the model to a collection
}
});
我创建了一个小提琴,因此您可以尝试一下。(我使用了提琴回声服务,因此这就是为什么我更改了URL并使用POST的原因)。如果运行它并检查控制台,则会看到正在记录用户集合,并且可以检查其models
属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句