9

I have two views, for simplicity sake a parent/child. The child is using trigger to throw an event. I am not seeing it in the handler of the parent. Is the below valid?

var parent = Backbone.View.extend({
    events: { "childevent": "run" },
    run: function(e) {
       console.log(e);
    }, 
    render: function() { /* render the child here */ }
});

var child = Backbone.View.extend({
    someAction: function() { this.trigger('childevent'); }
});
0

4 Answers 4

18

Figured it out! $(this.el).trigger('childevent'); works.

2
  • 3
    you can also try this.$el for the cached jQuery property
    – Gus
    Aug 3, 2012 at 2:38
  • and what if i'm following the policy that a view can access only the element its responsible for and its children? how do i event to the parent?
    – Hontoni
    Feb 11, 2013 at 20:08
2

Shouldn't it be events: { "childevent": "run" } instead? There is no way to access the actual anonymous function in this place in the code.

1
  • I actually had that, however it still doesn't work, I just typed it up wrong here. Good catch. Jul 20, 2011 at 2:33
2

Backbone store a jQuery reference to the view's node in this.$el property so you can spare some performance using it rather than re-compute the reference by $(this.el).

// use "this.$el.trigger()" to refer to jQuery's object
this.$el.trigger('childevent');
1

Obviously late, but for anyone else who comes across this:

the events property on a view is for auto-binding Html DOM events from components within the views el or $el elements, and the syntax involves both a UI event and a selector as the key in pair:

events: { "click #someButton", "clickHandler" }

To listen to events from other Models or Views, you use this.listenTo( target, ..... )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.