9

I 'm learning Backbone.js for a new app I'm building. I need to perform an AJAX call(REST SERVICE) to authenticate.

Where is the correct place for this call? In the Model, View or somewhere else? specifically related to Backbone.js MVC model.

<html>
<head>
<script src="lib/jquery-1.6.1.min.js"></script>
<script src="lib/json2.js"></script>
<script src="lib/underscore-min.js"></script>
<script src="lib/backbone-min.js"></script>   

<script language="javascript">
      $(function(){
         var LoginView = Backbone.View.extend({
          el: $("#login-form"),

          events: {
            "click #login": "login"
          },

          login: function(){
              alert("Hello");
           }
        });

        window.LoginView = new LoginView();
      });
    </script>   
  </head>
  <body>
    <form action="/login" id="login-form">
      Username: <input type="text" id="username"><br>
      Password: <input type="password" id="password"><br>
      <button id="login">Login</button>
    </form>
  </body>
</html>
0

3 Answers 3

13

Create an authentication Model, that stores the post state (username, password, remember me) as well as the response state (login failed, login accepted)...

App.Model.authentication= Backbone.Model.extend({
    defaults: {
        Username: "",
        Password: "",
        RememberMe: false,
        LoginFailed: false,
        LoginAccepted: false
    },
    url:"api/authentication"
});

Update the View to use the model:

   $(function () {
    var LoginView = Backbone.View.extend({
        model: new App.Model.authentication(),
        el: $("#login-form"),
        events: {
            "click #login": "login"
        },

        login: function () {
            this.model.save({username: this.$el.find("#username"),
                password: this.$el.find("#password")}, {
                success: function () {
                    /* update the view now */
                },
                error: function () {
                    /* handle the error code here */
                }
            });
        }
    });
}

);

Calling Model.Save() will issue a post request to the server, although in this instance on the server you're not actually saving anything, but check the credentials and sending back an object with the same model, but with the "LoginAccepted" field set appropriately.

Don't implement custom JQuery AJAX Posts - Its not in the spirit of backbone, which handles it all for you under the hood via its REST interface.

More details on the REST interface and the various REST Actions and URLS that backbone uses here: http://codebyexample.info/2012/04/30/backbone-in-baby-steps-part-3/

One more thing on the AJAX vs model.save() debate. If your application was a stateless chat room like IRC - which sends messages to other users in the chat room but doesn't save the messages centrally... would you throw away all of backbone's REST functionality and re-implement them with custom AJAX calls because you're not ACTUALLY 'saving', you're really just 'sending'. That would cost you a huge amount of work to re-implement functionality that's already there, just because of semantics. Always read model.save() as model.post() - its not just for saving - its for sending.

14
  • 1
    It's a hack to call Backbone save() on something you do not intend to change. And it's better to have a CurrentUser model that has current user data instead of another model just for auth purpose.
    – mvbl fst
    Jul 4, 2012 at 16:33
  • 2
    I'd say its a hack to intertwine ajax calls inside backbone when backbone is REST enabled and takes care of such things for you: save is just the name of a method that posts data to the server - it could just as well be named 'post', 'submit' or 'authenticate'. Our code does EXACTLY the same thing. Backbone carries out that exact $POST request for you. Jul 4, 2012 at 17:46
  • 1
    Here's the deal. You will learn if you have not already that you can NOT do everything you need in Backbone without hacking some concept. IMO using Ajax is less of a hack than using model.save() for auth (what exactly are you saving?)
    – mvbl fst
    Jul 4, 2012 at 18:40
  • @reach4thelasers: why do we pass an empty object in the save method and what real purpose does collection do when i have models. Jul 4, 2012 at 20:36
  • 1
    One more thing on the AJAX vs model.save() debate. If your application was a stateless chat room like IRC - which sends messages to other users in the chat room but doesn't save the messages centrally... would you throw away all of backbone's REST functionality and re-implement them with custom AJAX calls because you're not ACTUALLY 'saving', you're really just 'sending'. That would cost you a huge amount of work to re-implement functionality that's already there, just because of semantics. Always read model.save() as model.post() - its not just for saving - its for sending. Jul 5, 2012 at 10:21
11

You always start in the view because your DOM interactions (incl. form submits) happen in views.

Then, if I were you, I would add a custom method to the User model, and call the method from the view. The login method does not exactly fit with native Backbone sync as you're not trying to add / update / retrieve anything (mind that you DO NOT want to load user password or password hash from the server for security reasons). So you do a regular Ajax call without calling Backbone fetch(). So, here you go:

var UserModel = Backbone.Model.extend({
  ...
  checkLogin: function(name, password) {
    var self = this;
    $.post('/login', { name: name, password: password }, function(data) {
      self.set(data); // data should be in JSON and contain model of this user
    }, 'json').error(
      self.trigger('loginError'); // our custom event
    );
  }
});

And the view:

var UserView = Backbone.View.extend({
  events: {
    'click .login': 'loginSubmit'
  },

  initialize: function() {
     _.bindAll(this, 'loginSubmit', 'loginSuccess', 'loginError');
     this.model.bind('change', this.loginSuccess);
     this.model.bind('loginError', this.loginError);
  },

  loginSubmit: function() {
    var name = 'username', // you get it from some element
        password = '***'; // you get it from another element
    this.model.checkLogin(name, password);
  },

  loginSuccess: function() {
    alert ('You have been logged in');
    console.log(this.model); // should log loaded user model
  },

  loginError: function() {
    alert ('Problem with login');
  }
});

Make sure you pass the UserModel instance to the UserView instance, e.g.:

var userModel = new UserModel,
    userView = new UserView({ model: userModel });
3
  • Got a question. Why are you triggering loginSuccess when 'change'? May 20, 2013 at 19:33
  • Hey, I can't remember where this code sample is from but it looks like right above, in UserModel, I have self.set(data) in post callback. It might be emitting change on user model in set() method.
    – mvbl fst
    May 20, 2013 at 20:17
  • I believe it's worth pointing out about this example that the AJAX request (e.g., business logic) is placed in the model and not view, as it should be in a proper MVC implementation (backbone.js documentation also mentions putting business logic in models).
    – Caleb G
    Sep 25, 2013 at 2:26
0

ReST is NOT a standard, simply a spec and any practical developer will mix ReST and RPC when appropriate to do so. That said, neither of these answers pointed out the fact that the server response should return a token (sessionID, JSON web token, etc.) and delete the plain text password. Failing to do so introduces a security risk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.