Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js - controller properties from a view

I have a controller property called authenticated which defaults to false. However, in my login view I need to be able to set it to true. Also, in my logout view I need to be able to set it to false. How can I expose this property within the view?

var Controller = Backbone.Controller.extend({
    ...
    authenticated: false,

    login: function() {
        if(this.authenticated)
        {
            location.hash = '!/dashboard';
        } else {
            new LoginView();
        }
    },

    logout: function() {
        $.post('/admin/logout', {},
        function(resp){
        }, "json");

        this.authenticated = false;
        location.hash = '!/login';
    }
    ...
});
like image 911
Matthew Avatar asked Apr 30 '11 04:04

Matthew


1 Answers

Your controller is correctly doing the login and logout functionality. All you need to do is have your view fire backbone.js events and have the controller be registered to receive those.

Somewhere in your controller, you need something like:

var loginView = new LoginView(...);  // params as needed
loginView.bind("login_view:login", this.login);
loginView.bind("login_view:logout", this.logout);
loginView.render();

Also, you need to assure that the controller is set up to handle events, so something like this is needed in your initialize function:

_.extend(this, Backbone.Events);
_.bindAll(this, "login", "logout");

Your view will need the event code, so be sure to add the _.extend(...) call into its initialize.

In your view where appropriate, you need:

this.trigger("login_view:login");

and

this.trigger("login_view:logout");

As a final note, you want the controller to do the login and logout server calls. All you need from the view is an event and potentially a populated model or data otherwise. This data would be passed as a parameter in the trigger statement(s) and would be received as an argument in the login/logout functions. I have not included this in the code, however.

You basically want the view to manage the DOM and bubble up application events to the controller. The controller can then mediate with the server and manage any necessary views.

like image 181
Bill Eisenhauer Avatar answered Oct 29 '22 10:10

Bill Eisenhauer