VJAI
VJAI

Reputation: 32768

Specifying all the properties in Backbone.Model

I'm using Backbone in a mobile project. Let's say I've a sample class like this.

var Person = Backbone.extend({

});

The Person class the following properties firstName, lastName, age and gender. I want to specify all these properties in the class. So other developers know what are the properties they've to set for the instance. After going through the documentation I see there is a property called defaults which I could use.

var Person = Backbone.extend({
   defaults: {
      firstName: '',
      lastName: '',
      age: null,
      gender: null
   }
});

But I see the purpose of defaults property is different right? Not to let people know what are the properties the class contains. Is there any better way I can achieve this?

Upvotes: 5

Views: 62

Answers (2)

Eliran Malka
Eliran Malka

Reputation: 16263

You could write getter functions, so the model's attributes are directly available as a public API of the model.

That way, any developer using the model object will be able to view it's public properties (assuming she uses a decent IDE) without even opening the file for editing (why do that?), e.g.:

var Person = Backbone.extend({
    defaults: {
        firstName: '',
        // ...
    },
    getFirstName: function () {
        return this.attributes.firstName;
    }
    // ...
});

Upvotes: 1

Dethariel
Dethariel

Reputation: 3624

In our project we use defaults for this purpose. It solves the problem quite well, and may also serve as a documentation point. There's no other backbony-way of doing this which I know of. However, you can still use the old-fashioned comments :)

Upvotes: 1

Related Questions