admin管理员组

文章数量:1200976

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

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'); }
});
Share Improve this question edited Feb 11, 2013 at 21:24 Justin Thomas asked Jul 20, 2011 at 2:13 Justin ThomasJustin Thomas 5,8483 gold badges42 silver badges63 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 18

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

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

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

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

本文标签: javascriptBackboneJS Custom Event from Child ViewStack Overflow