Backbone.js - controller properties from the view

I have a controller property called authenticated , which defaults to false . However, in my view mode, I need to set it to true . Also, in my logout mode, I have to set it to false . How can I open this property in a 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'; } ... }); 
+6
source share
1 answer

The controller performs the input and output functions correctly. All you have to do is view the firebade.js events in view mode and register the controller to receive them.

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(); 

In addition, you must ensure that the controller is configured to handle events, so something like this is required in your initialization function:

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

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

If necessary, you need to:

 this.trigger("login_view:login"); 

and

 this.trigger("login_view:logout"); 

As a final note, you want the controller to make login and logout calls. All you need from a view is an event and a potentially populated model or data otherwise. This data will be passed as a parameter in trigger statements and will be taken as an argument in the input / output functions. However, I did not include this in the code.

Basically, you want the view to control the DOM and generate application events for the controller. Then the controller can interact with the server and manage any necessary views.

+7
source

Source: https://habr.com/ru/post/886996/


All Articles