Custom Backbone.js Event Switches

I am working on a simple application with excelent framework Backbone.js, and it would be nice if I could make a custom event selector with a basic representation, for example, this way it does not work, the js syntax is incorrect:

return Backbone.View.extend({ events: { 'click ' + someConfigSelector: 'doSomethink' } }) 

Is there any other way to configure events in Backbone modes?

+4
source share
3 answers

Check out this script: http://jsfiddle.net/phoenecke/hyLMz/1/

You can use the function for events instead of an object.

 return Backbone.View.extend({ events: function() { // add some normal events to the hash var e = { 'click #foo': 'doSomething1', 'click #bar': 'doSomething2' }; // add one where key is calculated e['click ' + someConfigSelector] = 'doSomething'; // return events hash return e; } }); 

Thus, you can add your events when the key is calculated based on your configuration.

+7
source

I prefer the method below for dynamic events, as this function will be called at any time by delegateEvent .

In docs on the Event deletion, which is called after the view initialize function is executed, you can use this technique to create events dynamically:

 var TestView = Backbone.View.extend({ events: function () { var evt = {}; evt['click ' + this._extraSelector] = '_onButtonClick'; return evt; }, initialize: function(config) { // passed in the selector, or defaulted this._extraSelector = config.extraSelector || "BUTTON.default"; }, _onButtonClick: function() { } }); var v = new TestView({ extraSelector: 'BUTTON.sample' }); 
+1
source

You can do it as follows:

 return Backbone.View.extend({ events: { }, initialize:function() { this.events['click ' + someConfigSelector] = 'doSomethink'; } }) 

But this somewhat violates the agreement on how events are declared in the trunk and makes the code more difficult to read. Maybe someone has a better approach.

0
source

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


All Articles