Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable for selectors in events

for some reason I need to use a variable as the selector for events in backbone, but I can't figure how to do this :

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

I have to use a different scope and I can't do "click .close" : "closeWindow".

Thx for your help.

like image 579
Flyingbeaver Avatar asked Feb 22 '23 05:02

Flyingbeaver


2 Answers

I had a look at Backbone.js's source code and found out that if your view's events is a function then the function is called and it's return value is used as the events object.

This means that your code can be changed like this:

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 the interesting part of the source code:

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

Update:

Example is available on JSFiddle HERE**

like image 130
kubetz Avatar answered Feb 24 '23 17:02

kubetz


I'm not sure that you'll be able to use a variable there. You could use the built-in Events methods (see documentation) to add a custom listener, then add an event listener to window.parent.document to trigger that custom event (use the Events.trigger method).

That said, it would be much easier to decouple this event from Backbone entirely (unless you don't want to do that), 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 that should work, although I haven't tested it (and there may be one or two syntactical errors!)

like image 31
SquareFeet Avatar answered Feb 24 '23 19:02

SquareFeet