Search code examples
backbone.jsmixins

Extending Backbone.Model through mixins


I'm recently started playing with Backbone.js. I want to apply custom validation mechanism to my model classes and I decided to go with mixin classes. Now the question is it a good idea to attach the mixin to the Backbone.Model class like below,

_.extend(Backbone.Model.prototype, MyApp.ValidationMixin)

or can I create a base model AppModel from which all the application models extends and I'll attach the mixin to the base model.

var AppModel = Backbone.Model.extend({});
_.extend(AppModel.prototype, MyApp.ValidationMixin)

Is there any problem I'll face if I go with the first approach?


Solution

  • In general, the first approach is OK for this specific case (adding a Validation Mixin to the Backbone Model) but your validation Mixin may get erased by other libraries doing the same (it's sometimes hard to 'pick and choose' the functionality of additional Backbone libraries).

    The second approach is safer and is the usual recommended approach as can be seen in various Backbone's app boilerplates.

    Both are technically the same, as long as you live in your own little "app bubble".