0
votes

My app is Backbone.js for client-side, Express.js for back-end.

I have problems with syncing with all parts of my API, using the backbone model and collection(they use urlRoot: "/users"). I'm allowed to use only GET or POST, no PUT or DELETE. *I'm not allowed to use more models* Not allowed to use jQuery ajax

My API

add new user: I need to make a POST to /users with JSON of new data. So I did it just fine with - this.model.save({new data...})

list all users: My API for that, responses to GET /users, with the right handler - so, this.collection.fetch() - works fine.

Log-In: My API accepts POST to /users/login for that. How can I add a function "logIn" to my model, that will use custom sync/pass options.url to sync - or any other way - that will POST to /users/login ?

Log-Out: API accepts POST to /users/logout - how to send this request using my backbone model ?

User By ID: Same question here for GET /users/:id

Update user: POST /users/:id - same question again.

--- So actually, the question in short is ---

What is the best way (or the most "right"), to implement methods of a backbone model, that are similar to "model.save()" - but just POST/GET to a bit different path then urlRoot ?

1

1 Answers

1
votes

You probably have a couple options here. One would be structuring your models in a way that supports the urls you want. For instance, have a User model and a Session model that deal with updating the user and managing the logged in state separately.

The other thing you should probably do is to use the url method in your models.

Something like this in your User model. (Note: using urlRoot instead of url here is identical, but this is the correct approach for anything more complicated that is needed in the url)

url : function() {
  var base = "/users/";
  if(this.isNew()) {
    return base;
  } else {
    return base + this.get("id");
  }
}

You could extend this same concept to work in your Session model for handling logout vs login based on if the Session is new or not.

Update:

If you must use the same model, the best thing would be to totally bypass the Backbone.sync method and write a custom AJAX call with success/error handlers that know how to clean things up.

login : function() {
  $.post("/users/login", {success: function (response) {
      // Update user as needed
    }, error: function (xhr, response) {
      // Handle errors
    }
  }
}