学习backbone.js。我是否正确处理集合?
Learning backbone.js. Am I handling collections correctly?
我来自 ruby/rails 背景,所以我在思考关于 UDEMY 的 backbone 课程练习时遇到了一些麻烦。有人可以告诉我我是否犯了任何错误,如果是这样,该如何解决?这个练习是关于集合的,我需要输出为 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" }
因此 Collection
可以接受 Model
数组或仅包含数据的对象数组,这些数据将传递给集合中使用的模型构造函数。
您也可以使用 Collection#findWhere 到 return 只是第一个找到的模型,而不是像 where
中那样的模型数组
我还发现你忘了在 default
部分后添加逗号
default: {
registrationNumber: "XXX-XXX",
color: "beige"
}, // here should be a coma
我来自 ruby/rails 背景,所以我在思考关于 UDEMY 的 backbone 课程练习时遇到了一些麻烦。有人可以告诉我我是否犯了任何错误,如果是这样,该如何解决?这个练习是关于集合的,我需要输出为 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" }
因此 Collection
可以接受 Model
数组或仅包含数据的对象数组,这些数据将传递给集合中使用的模型构造函数。
您也可以使用 Collection#findWhere 到 return 只是第一个找到的模型,而不是像 where
我还发现你忘了在 default
部分后添加逗号
default: {
registrationNumber: "XXX-XXX",
color: "beige"
}, // here should be a coma