這裏是我的完整解決這個問題: jsFiddle Complete example
@spotmat把我在正確的方向,但我需要添加額外的功能。下面是一個需要解決的幾個項目:
- 集合構造器需要處理pased給它的數據需要
- 當一個模型IsLocked屬性更新的集合進行重新驗證
我'不知道是否將綁定屬性添加到集合是一個好主意,但是找到一些有趣的東西,我學到了很多東西。
var log = {};//this is for debugging
_.extend(log, Backbone.Events);
var Car = Backbone.Model.extend({});
var Cars = Backbone.Collection.extend({
model: Car,
url: "scripts/data/Cars.json",
initialize: function() {
var _this = this;
this.isValid = false; //user should bind to "change:isValid"
this._isPending = false; //This is so that
this.bind("add", this.modelAdded, this);
this.bind("reset", this.modelsAdded, this);
if (this.length > 0) {
//Model passed in though the constructor will not be binded
//so call modelsAdded
this.modelsAdded(this);
}
},
modelsAdded: function (collection) {
this._isPending = true
log.trigger("log", ["modelsAdded: " + collection.length]);
collection.each(this.modelAdded, this); //Do nut remove "this" param. It need when modelAdded gets called
this._isPending = false
this._validate();
},
modelAdded: function (model) {
log.trigger("log", ["modelAdded: " + model.get("Model") + "; IsLocked: " + model.get("IsLocked")]);
//!!!for each model added to the colleciton bind
//its IsLocked property to the collection modelIsLockedChange function
model.bind("change:IsLocked", this.modelIsLockedChanged, this);
if (this._isPending == false) {
this._validate();
}
},
modelIsLockedChanged: function (model) {
log.trigger("log", ["modelIsLockedChanged:" + model.get("Model") + "; IsLocked: " + model.get("IsLocked")]);
this._validate();
},
_validate: function() {
var isValid = true;
this.each(function (model) {
if (model.get("IsLocked") == false) {
isValid = false
}
});
if (this.isValid != isValid) {
this.isValid = isValid
cars.trigger("change:isValid", [this.isValid])
}
},
});
這種觀點是僅用於調試
var Logger = Backbone.View.extend({
el: $("#output"),
initialize: function(){
log.bind("log", this.logMessage, this)
},
render: function(){
return $(this.el).html("");
},
logMessage: function(message){
$(this.el).find("ul").append("<li>" + message[0] + "</li>");
}
})
下面的代碼是用來測試集合
var logger = new Logger();
log.bind("log", function(message){
console.log(message[0]);
});
var carsData = [
{ "Model": "Chevy Camero", "Year": 1982, "IsLocked": true },
{ "Model": "Ford F-150", "Year": 2011, "IsLocked": false }
]
var cars = new Cars(carsData);
cars.bind("change:isValid", function(isValid){
log.trigger("log", ["change:isValid: " + isValid]);
});
cars.add({ "Model": "Toyota Tacoma", "Year": 2006, "IsLocked": true });
cars.at(1).set({ "IsLocked": true });
感謝您的回答。我相信你已經指出了我的正確方向。欣賞在初始化時應該創建的有效信息。當我完成我的工作解決方案後,我會發布它。 – 2012-01-27 04:36:11