onlineracoon
onlineracoon

Reputation: 2970

Backbone.js non-rest (user) model

I have the following user model:

var UserModel = Backbone.Model.extend({
  urlRoot: 'user',
  defaults: {
    fullName: null,
    email: null,
    password: null
  }
});

Now we can CRUD (sign up, update information, delete, and get a user) but what about:

How would I expand my UserModel to make this possible?

Upvotes: 0

Views: 1180

Answers (3)

Greg
Greg

Reputation: 313

There's nothing wrong with making your own methods that complement the built-in fetch and save and which do regular $.ajax calls. It's perfectly fine to introduce your own reset and activate methods, for instance, that do a regular $.post to dedicated server URIs to reset the password and update the user instance accordingly.

Upvotes: 0

onlineracoon
onlineracoon

Reputation: 2970

I got the answer myself. So once again I needed non-crud operations like:

  • POST /users/restore-password
  • POST /users/activate

Solution:

function nonCrudOperation(urlSegment, requestMethod){
  return Backbone.sync.call(this, null, this, _.extend({
    url: this.url() + '/' + urlSegment,
    type: requestMethod
  }, options));
};

var UsersModel = Backbone.Model.extend({
  urlRoot: 'user',
  activate: function(options){
    return nonCrudOperation.call(this, 'activate', 'POST');
  },
  restorePassword: function(options){
    return nonCrudOperation.call(this, 'restore-password', 'POST');
  }
});

Upvotes: 5

rjz
rjz

Reputation: 16510

It might make better sense to separate out a session model with the login as its endpoint and use this to complete the login transaction. Something along these lines:

var UserSessionModel = Backbone.Model.extend({
  urlRoot: 'users/login',
  defaults: {
    email: null,
    password: null
  }
});

After a successful login, you might then swap out the session for an actual user:

var session = new UserSessionModel({ username: 'foo', password: 'bar' }),
    user;

session.save({ 
  success: function (attrs) {
    user = new UserModel(attrs);
  }
});

Upvotes: 3

Related Questions