Alex
Alex

Reputation: 5724

Declaring a backbone model with defaults relative to other fields

How can I get the following code to do default based on other model values? This is roughly what I have

var Model = Backbone.Model.extend({
    defaults:{
        name:"",
        surname:"",
        fullTextString:""
    }
});
model = new Model({name"John", surname:"Doe", fullTextString:"John"+" "+"Doe"})

What I want is:

Backbone.Model.extend({
    defaults:{
        name:"",
        surname:"",
        fullTextString:name+" "+surname
    }
});

Upvotes: 2

Views: 73

Answers (2)

John Munsch
John Munsch

Reputation: 19528

Given that you want one of the attributes to be a calculated value based upon both passed in values and, potentially, default values (for example, if they specify a {surname: "Munsch"} but provide no name), I think the easiest thing would be to add an initializer like so:

var Model = Backbone.Model.extend({
    defaults:{
        name:"",
        surname:""
    },
    initialize: function() {
        this.set({fullTextString: this.get("name") + " " + this.get("surname")});
    }
});

model = new Model({name:"John", surname:"Doe"});
model2 = new Model({surname:"Doe"});

console.log("model fullTextString: ", model.get("fullTextString"));
console.log("model2 fullTextString: ", model2.get("fullTextString"));

Upvotes: 1

sQVe
sQVe

Reputation: 2015

Default values is only used when you do not set the values, so what you want is not possible.

I would use the following to get the functionality you want:

var Model = Backbone.Model.extend({
    defaults: {
        firstName: "",
        lastName : ""
    },

    fullName: function() {
        return this.get("firstName") + " " + this.get("lastName");
    },

    get: function( attr ) {
        if ( typeof this[attr] === "function" ) {
            return this[attr]();
        }
        return Backbone.Model.prototype.get.call(this, attr);
    }
});

This way you can initialize your model this way:

model = new Model({firstName: "John", lastName: "Doe"});

And use model.get("fullName") to get the name "John Doe".

Upvotes: 1

Related Questions