0
votes

I have a model and collection defined in Backbone like so:

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

However, when working with these models inside a Collection, the custom fields listed are all not defined. What have I missed here?

1
Model : DeviceModel => model : DeviceModel ? (lowercase m) - WiredPrairie
@WiredPrairie (facepalm) It was that, staring me in the face all along. Thanks so much. - Nidonocu

1 Answers

-1
votes

You may use the defaults Model attribute to enforce default values like this:

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

From Backbone documentation if you create your model with the new operator all properties in defaults will get copied to the new object, so it depends on the way you create your model objects.