theJava
theJava

Reputation: 15034

model.set does not persist values in backbone.js

this.save(userDetails, {
    success: function (user, result, xhr) {
        this.set({userName: user.userName});
    },

    error: function (user, result, xhr) {

    }
});

return this.userName;

When i try to set my userName with the response i get, it does not set. When i try to alert return this.userName, it says me undefined.

Upvotes: 0

Views: 198

Answers (2)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

user is the Backbone model, so essentially it seems like you are trying to do this:

user.set({userName: user.get('userName'});

If userName is a value that comes back from your server, it is probably already set on the model.

In your success handler, try this:

console.log(user.get('userName'));

You do not access a model's attributes using model.userName, you use model.get('userName').

Upvotes: 1

Nishant Jani
Nishant Jani

Reputation: 1993

A Couple of things here :

  1. When the success function is called (the call back after save) , it return the entire model that is saved , so you might try :

    success : function(model){ model.set({userName : model.userName}); }

  2. The save is asynchronus , so you might want to do something like :

    this.model.on('sync',function(model){ model.set({userName : model.userName}); //rest of programming; })

Upvotes: 1

Related Questions