Max Koretskyi
Max Koretskyi

Reputation: 105527

What's the convention to define backbone models class properties/fields

I want to define which properties a class has. We use backbone for OOP. I've read that backbone model gets its properties when initialized, and only methods are defined for the class using extend. But I think that having explicitly defined class fields adds to readability. Is there some convention on how to do that?

Upvotes: 0

Views: 71

Answers (2)

mu is too short
mu is too short

Reputation: 434785

From the fine manual:

extend Backbone.Model.extend(properties, [classProperties])
[...] as well as optional classProperties to be attached directly to the constructor function.

Similarly for collections, routers, and views.

To define a class method on a model:

var M = Backbone.Model.extend({
    // instances methods and properties go here...
}, {
    some_class_method: function() { ... }
});

M.some_class_method(); // Then this will work.

Upvotes: 2

JBoulhous
JBoulhous

Reputation: 952

Backbone models hold data in the attributes key so

model = new Backbone.Model({foo:'bar'});
model.attributes.foo === 'bar';

and you should access data with model.get() model.set() which will manage events firing.

you can also hook into Backbone models creations using initilize method or by rewriting constructor (you may look at MarionetteJS views for an inspiration).

Upvotes: 0

Related Questions