[英]Backbone.js validate collection
Backbone.js為模型提供驗證。 但是沒有一種簡單的方法來檢查集合中的所有模型是否有效。 集合沒有.isValid
屬性。
我使用這樣的黑客:
_.isEmpty(_.filter(myCollection.models, function(m) {return m.validationError;}))
是否有更優化的方式來“驗證”收集?
用一些方法怎么樣?
var hasErrors = _.some(myCollection.models, function(m) {
return m.validationError;
});
lodash.js支持這樣的構造(使用“_.pluck”回調速記):
_.some(myCollection.models, 'validationError');
我知道這是一個老問題,但請看看我對這個問題的決定。 簡而言之,它可以作為github repo backbone-collection-validation使用 。 現在,詳細說明。 要像這樣驗證集合
Collection = Backbone.Collection.extend({
validate: function (collection) {
var nonExistIds = [];
_.forEach(collection, function (model) {
var friends = model.get('friends');
if (friends && friends.length) {
for (var i = friends.length - 1; i >= 0; i--) {
if (!this.get(friends[i])) {
nonExistIds.push(friends[i]);
}
}
}
}, this);
if (nonExistIds.length) {
return 'Persons with id: ' + nonExistIds + ' don\'t exist in the collection.';
}
}
})
你需要擴展你的Backbone
//This implementation is called simple because it
// * allows to set invalid models into collection. Validation only will trigger
// an event 'invalid' and nothing more.
var parentSet = Backbone.Collection.prototype.set;
Backbone.Collection.prototype.set = function (models, options) {
var parentResult = parentSet.apply(this, arguments);
if (options && options.validate) {
if (!_.isFunction(this.validate)) {
throw new Error('Cannot validate a collection without the `validate` method');
}
var errors = this.validate(this.models);
if (errors) {
this.trigger('invalid', this, errors);
}
}
return parentResult;
};
或者這個
//This implementation is called advanced because it
// * doesn't allow to set invalid models into collection.
var parentSet = Backbone.Collection.prototype.set;
Backbone.Collection.prototype.set = function (models, options) {
if (!options || !options.validate) {
return parentSet.apply(this, arguments);
} else {
if (!_.isFunction(this.validate)) {
throw new Error('Cannot validate a collection without the `validate` method');
}
var clones = [];
_.forEach(this.models, function (model) {
clones.push(model.clone());
}, this);
var exModels = this.models;
this.reset(clones);
var exSilent = options.silent;
options.silent = true;
parentSet.apply(this, arguments);
var errors = this.validate(this.models);
this.reset(exModels);
if (typeof exSilent === 'undefined') {
delete options.silent;
} else {
options.silent = exSilent;
}
if (errors) {
this.trigger('invalid', this, errors);
return this;
} else {
return parentSet.apply(this, arguments);
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.