user3608074
user3608074

Reputation:

Backbone object defaults not working

I'm learning about Backbone.js and I'm following a tutorial. In the tutorial a Person object is created with default values. But when I try to access these value with the command var person = new Person; and then see if the object is created with person.get('name') command in console I get undefined back. In the tutorial this should print John Doe. Why I'm a getting undefined back when the Person object has defaults?

// main.js
var Person = Backbone.Model.extend ({
    default: {
        name: 'John Doe',
        age : 30,
        job : 'Web designer'
    },
    work : function() {
        return this.get('name') + ' is working!!';
    }
});

<head>
    <script src="js/underscore.js"></script>
    <script src="js/jquery-1.11.1.min.js"></script>
    <script src="js/backbone.js"></script>
    <script src="js/main.js"></script>
</head>

If I print the person to a JSON model with person.toJSON() it returns an empty object. But it should not be empty because of the default value.

Upvotes: 0

Views: 222

Answers (3)

Lorenzo B
Lorenzo B

Reputation: 33428

The property you should use is defaults and not default.

var Person = Backbone.Model.extend({
    defaults: {
        name: 'John Doe',
        age: 30,
        job: 'Web designer'
    }
});

For further info I would suggest to take a look at What is a model? and obvioulsy to Backbone documentation.

Upvotes: 1

StateLess
StateLess

Reputation: 5402

property name is defaults

var Person = Backbone.Model.extend ({
    defaults: {
        name: 'John Doe',
        age : 30,
        job : 'Web designer'
    },
    work : function() {
        return this.get('name') + ' is working!!';
    }
});

check this

Upvotes: 2

joews
joews

Reputation: 30330

The property is defaults, not default:

var Person = Backbone.Model.extend ({
    defaults: {
       // ...
    }
});

Backbone docs

Upvotes: 2

Related Questions