Custom event in backbone.js without binding

I am looking for a better way to implement PubSub type functionality using Backbone. I am currently seeking this, but I am looking for a better way to do this.

Routing Code Example

var AppRouter = Backbone.Router.extend({ customEvents: _.extend({}, Backbone.Events), routes: { "login": "login" }, //Injecting custom event login: function(){ this.before(function () { app.showView('#Content', new LoginView({customEvents:this.customEvents}), "login", true); }); }, //Injecting custom event otherView: function(){ this.before(function () { app.showView('#Header', new OtherView({customEvents:this.customEvents}), "login", true); }); }, ..... more code }); 

View code example. Note that I am using bind to listen for customEvent. This works great, but is looking for an alternative method

 LoginView = Backbone.View.extend({ initialize: function(options){ this.customEvents = options.customEvents; this.customEvents.bind('app:loggedin', this.loggedIn); }, loggedIn: function(){ console.log("LOG CHANGED"); }, ...more code 

I would rather save my events with the rest of the events that I use in my view. Not sure how to achieve this. Should I extend the View class?

What I would like to do in my ideas

  LoginView = Backbone.View.extend({ events: { "app:loggin" : "loggedIn" }, loggedIn: function(){ console.log("LOG CHANGED"); }, ...more code 
+4
source share
1 answer

Gist: https://gist.github.com/vermilion1/5600032

Demo: http://jsfiddle.net/vpetrychuk/3NVG9/1

Code Preview:

 // -- BASE VIEW ------------------ var BaseView = Backbone.View.extend({ constructor : function (options) { Backbone.View.prototype.constructor.apply(this, arguments); this._eventAggregator = options && options.eventAggregator || this; this._parseTriggers(); }, _parseTriggers : function () { _.each(this.triggers || {}, function (fn, event) { var handler = this[fn]; if (_.isFunction(handler)) { this.listenTo(this._eventAggregator, event, handler); } }, this); } }); // -- TEST ------------------ var View = BaseView.extend({ triggers : { 'hello' : 'helloHandler', 'bye' : 'byeHandler' }, helloHandler : function (name) { console.log('hello, ' + name); }, byeHandler : function (name) { console.log('bye, ' + name); } }); var view1 = new View(); view1.trigger('hello', 'dude 1'); // -> hello, dude 1 view1.trigger('bye', 'dude 1'); // -> bye, dude 1 var vent = _.extend({}, Backbone.Events); var view2 = new View({eventAggregator:vent}); vent.trigger('hello', 'dude 2'); // -> hello, dude 2 vent.trigger('bye', 'dude 2'); // -> bye, dude 2 
0
source

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


All Articles