Search code examples
javascriptbackbone.js

Backbone.js: Using the same model value to set another value of same model


I'm trying to set a property of a model using another property but I am getting undefined.

This is the example:

var TodoItem = Backbone.Model.extend({
    defaults: {
        status: "incomplete",
        relationalStatus: this.status,
    },
});

When I try getting the value using todoItem.attributes. I just see an empty string in the relationlStatus value.

Why is not getting the value?


Solution

  • You would need to set this during the initialize phase. this.status is referring to the outer scope, it's not currently scoped within the model.

    Example of using initialize.

    http://jsbin.com/wuqef/1/edit

    var TodoItem = Backbone.Model.extend({
        defaults: {
            status: "incomplete",
            relationalStatus: null,
        },
    
      initialize: function() {
    
        // Set the relationalStatus to the status property
        this.set('relationalStatus', this.get('status'));
    
      }
    
    });