2
votes

I'm new to Backbone.js and in my recent project I need a custom validation mechanism for models. I see two ways I could do that.

  1. Extending the Backbone.Model.prototype

    _.extend(Backbone.Model.prototype, { ... });

  2. Creating custom model that inherit from Backbone model

    MyApp.Model = Backbone.Model.extend({ ... });

I quite unsure which one is a good approach in this case. I'm aware that overriding prototype is not good for native objects but will that applies to backbone model prototype as well? What kind of problems I'll face if I go with the first approach?

2

2 Answers

1
votes

You are supposed to use the second approach, that's the whole point of Backbone.Model.extend({}).

It already does your first approach + other near tricks to actually setup a proper inheritance chain (_.extend is only doing a copy of the object properties, you can look up the difference in code for Backbone's extend() and Underscore's _.extend, they are very large and not very interesting. Just extending the .prototype isn't enough for 'real' inheritance).

When I first read your question, I misunderstood and thought you were asking whether to extend from your own Model Class or directly extend from Backbone Extend. It's not your question, so I apologize for the first answer, and just to keep a summary here: you can use both approach. Most large websites I saw or worked on first extend from Backbone.Model to create a generic MyApp.Model (which is why I got confused, that's usually the name they give to it :)), which is meant to REPLACE the Backbone.Model. Then for each model (for instance User, Product, Comment, whatever..), they'll extend from this MyApp.Model and not from Backbone.Model. This way, they can modify some global Backbone behavior (for all their Models) without changing Backbone's code.

1
votes

_.extend(Backbone.Model.prototype, {...mystuff...}) would add your property/ies to every Backbone.Model, and objects based on it. You might have meant to do the opposite, _.extend({...mystuff...}, Backbone.Model) which won't change Backbone itself.

If you look at the annotated Backbone source you'll see lines like

_.extend(Collection.prototype, Events, { ... Collection functions ...} )

This adds the Events object contents to every Collection, along with some other collection functions. Similarly, every Model has Events:

 _.extend(Model.prototype, Events, { ... Model functions ...})

This seems to be a common pattern of making "classes" in Javascript:

function MyClass(args) {
  //Do stuff
}

MyClass.prototype = {....}

It's even used in the Firefox source code.