0

我在 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 中使用这些模型时,列出的自定义字段都没有定义。我在这里错过了什么?

4

1 回答 1

-1

您可以使用defaultsModel 属性来强制执行默认值,如下所示:

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将被复制到新对象,因此这取决于您创建模型对象的方式。

于 2013-03-26T12:14:43.033 回答