我在Backbone中定义了一个模型和集合,如下所示:
$(document).ready(function () {
DeviceModel = Backbone.Model.extend({
urlRoot: '/ajax/mvcDevices',
validationRules: {
name: [{ rule: 'required'}],
mac: [
{ rule: 'required' },
{ rule: 'isMacAddress' }
],
speed: [{ rule: 'required'}]
},
preprocess: {
name: ['clean', 'trim'],
speed: ['clean', 'trim']
}
});
DeviceCollection = Backbone.Collection.extend({
url: '/ajax/mvcDevices',
Model: DeviceModel
});
});
但是,在Collection中使用这些模型时,列出的自定义字段都未定义。我在这里错过了什么?
答案 0 :(得分:-1)
您可以使用defaults
Model属性强制执行默认值,如下所示:
var DeviceModel = Backbone.Model.extend({
urlRoot: '/ajax/mvcDevices',
defaults: {
validationRules: {
name: [{ rule: 'required'}],
mac: [
{ rule: 'required' },
{ rule: 'isMacAddress' }
],
speed: [{ rule: 'required'}]
},
preprocess: {
name: ['clean', 'trim'],
speed: ['clean', 'trim']
}
}
});
var DeviceCollection = Backbone.Collection.extend({
url: '/ajax/mvcDevices',
Model: DeviceModel
});
var collection = new DeviceCollection();
var model = new DeviceModel({id: 1});
collection.add(model);
console.log(collection.get(1).get('validationRules'));
console.log(collection.get(1).get('preprocess'));
从Backbone文档中,如果使用new
运算符创建模型,defaults
中的所有属性都将复制到新对象,因此它取决于您创建模型对象的方式。