Using a variable for selectors in events

for some reason I need to use the variable as a selector for events in the trunk, but I cannot figure out how to do this:

app.views.Selfcare = Backbone.View.extend({ events: { click window.parent.document .close : "closeWindow" }, closeWindow: function() { //code } }); 

I need to use a different area and I can not do "click.close": "closeWindow".

Thanks for your help.

+4
source share
2 answers

I turned to the source code of Backbone.js and found out that if your type of events is a function, then the function is called, and the return value is used as an events object.

This means that your code can be changed as follows:

 app.views.Selfcare = Backbone.View.extend({ events: function() { var _events = { // all "standard" events can be here if you like } _events["events" + "with variables"] = "closeWindow"; return _events; }, closeWindow: function() { //code } }); 

THIS is an interesting part of the source code:

 if (_.isFunction(events)) events = events.call(this); 

Update:

An example is available in JSFiddle HERE **

+7
source

I'm not sure if you can use the variable there. You can use the built-in event methods (see documentation ) to add a custom listener, and then add an event listener to window.parent.document to call this (use the Events.trigger method).

However, it would be much easier to separate this event from the Backbone (if you don't want it) and go down the addEventListener route:

 app.views.Selfcare = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'render', 'closeWindow'); if(this.options.clickTarget) { this.options.clickTarget.addEventListener('click', this.closeWindow, false); } }, render: function() { // Render to the DOM here return this; // as per Backbone conventions }, closeWindow: function() { // Stuff here } }); // Usage: var mySelfcare = new app.views.Selfcare({ clickTarget: window.parent.document }); 

I think this should work, although I have not tested it (and there may be one or two syntax errors!)

+1
source

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


All Articles