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
});
});

ただし、コレクション内でこれらのモデルを操作する場合、リストされているカスタム フィールドはすべて定義されていません。ここで何を見逃したのですか?

4

1 に答える 1

-1

Model 属性を使用して、次のdefaultsようにデフォルト値を適用できます。

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'));

バックボーンのドキュメントから、new演算子を使用してモデルを作成すると、すべてのプロパティがdefaults新しいオブジェクトにコピーされるため、モデル オブジェクトの作成方法によって異なります。

于 2013-03-26T12:14:43.033 に答える