0

Suppose that I have the following view:

var SampleView = Backbone.View.extend({
    initialize: function() {
        this.child_element = this.$('#new-catalog>button:first');                
    },
    events: {
        'click #new-catalog>button:first': function() { alert('clicked'); },
    },
    el: '#some-element',
});

If you have some non trivial selection for custom children items (like my child_element selected with #new-catalog>button:first, is it possible to avoid redefining it in the events property and instead refer to this.child_element?

Of course I can do this.child_element.on('click', ..., but I'd like to use the provided events dictionary.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
pistacchio
  • 56,889
  • 107
  • 278
  • 420
  • I don't think you can do that directly, if you look at the delegateEvents method in the backbone.js source code you'll see that it uses a regex to split the key part of the events hash into a eventName and a selector string. – Jack Oct 12 '12 at 14:15
  • 1
    View events in Backbone are bound via jQuery's `delegate` so you're stuck with jQuery selectors. There's nothing stopping you from binding events directly to DOM elements in the usual jQuery manner though, just be sure to unbind the handlers to avoid zombies. You'd be better off simplifying your selectors with CSS classes to simplify your selectors and make your events less dependent on the specific DOM structure you're using. – mu is too short Oct 12 '12 at 17:22

0 Answers0