Justin Thomas
Justin Thomas

Reputation: 5848

Backbone.JS Custom Event from Child View

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'); }
});

Upvotes: 9

Views: 5069

Answers (4)

marcopeg
marcopeg

Reputation: 1228

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');

Upvotes: 2

Montagist
Montagist

Reputation: 401

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, ..... )

Upvotes: 1

Justin Thomas
Justin Thomas

Reputation: 5848

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

Upvotes: 18

julx
julx

Reputation: 9091

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

Upvotes: 2

Related Questions