简体   繁体   中英

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.

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 **

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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM