26ph19
26ph19

Reputation: 393

Backbonejs setter returns undefined

I am using Backbone.Mutators.js js plugin to override setter and getter. Below is my Model

var BuyerModel = Backbone.Model.extend({
    mutators: {
        fullName: {
            get: function () {
                return this.firstName + ' ' + this.lastName;
            }
        }
    }
});

Below is how I am setting and getting full name.

    var buyerModel = new BuyerModel();

    buyerModel.set({ firstName: 'Joe', lastName: 'Bloggs' });

    console.log(buyerModel.get('fullName')); // returns undefined undefined
    console.log(buyerModel.get('firstName')); // return Joe
    console.log(buyerModel.get('lastName')); // returns Bloggs

Why fullName returns undefined undefined and how to fix it?

Upvotes: 0

Views: 57

Answers (2)

Ram
Ram

Reputation: 144669

Attributes of the model is stored in it's attributes property, those are not direct properties of the instance, you should use the get method:

return this.get('firstName') + ' ' + this.get('lastName');

Upvotes: 1

Daniel Nill
Daniel Nill

Reputation: 5747

I don't know about the mutators plugin but it would appear you need to change your function to

return this.get('firstName') + ' ' + this.get('lastName');

This means the the scope of the function is the the model not the attributes sub object.

Upvotes: 1

Related Questions