我有 ruby/rails 背景,所以我在思考 UDEMY 上的主干类(class)练习时遇到了一些困难。有人可以告诉我是否犯了任何错误,如果有的话如何修复?这个练习是关于集合的,我需要输出为 console.logs
var Vehicle = Backbone.Model.extend({
default: {
registrationNumber: "XXX-XXX",
color: "beige"
}
urlRoot: "/api/vehicle",
start: function(){
console.log("Vehicle started");
}
});
var Vehicles = Backbone.Collection.extend({
model: Vehicle,
url:"api/vehicles"
});
var vehicles = new Vehicles([
new Vehicle({car1: {registrationNumber = "XLI887", color = "Blue"} }),
new Vehicle({car2: {registrationNumber = "ZNP123", color = "Blue"}}),
new Vehicle({car3: {registrationNumber = "XUV456", color = "Grey"}})
]);
var blueCars = vehicles.where({ color: "Blue"});
var specificRegistration = vehicles.where({ registrationNumber:"XLI887"});
console.log("blue cars:", blueCars);
console.log("Registration #:", specificRegistration);
console.log("to JSON:", vehicles.toJSON());
最佳答案
错了
new Vehicle({car1: {registrationNumber = "XLI887", color = "Blue" }})
并且应该替换为
new Vehicle({registrationNumber: "XLI887", color: "Blue" })
或与此相关的事件
{registrationNumber: "XLI887", color: "Blue" }
so Collection
可以接受 Model
数组或仅包含数据的对象数组,这些数据将传递给集合中使用的模型构造函数。
您还可以使用Collection#findWhere仅返回第一个找到的模型,而不是像 where
我还发现您忘记在 default
部分后添加逗号
default: {
registrationNumber: "XXX-XXX",
color: "beige"
}, // here should be a coma
关于javascript - 学习backbone.js。我是否正确处理集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29832013/