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;
loca开发者_JAVA技巧tion.hash = '!/login';
}
...
});
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.
精彩评论