Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify children only in the Backbone.js event handler?

I have a view which has a view inside it (the same view in fact, its recursive). I want only the internal view to handle the event from an 'a' onclick event. I tried to do this by specifying only the direct children in the selector, but it doesnt work.

iv tried:

events: { 
    'click >a': 'toggle'
},

and

events: { 
    'click > a': 'toggle'
},

but they dont work, any suggestions? (Note: doing things like using tags and classes wont work because the view is recursive (meaning that both the inner and outer have the same event definitions)

like image 689
chacham15 Avatar asked Nov 21 '11 14:11

chacham15


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

How do you trigger an event in the backbone?

Backbone. js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it.

Is Backbone JS frontend or backend?

Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.


2 Answers

I have run into the same issue, and have solved it by stopping the propagation of the event in my child view. For example...

events: {
    'click a': 'toggle'
},

toggle: function (e) {

    // Stop event here.
    e.stopImmediatePropagation();

    // Do more stuff...

}

This does not answer your question of how to specify specific child selectors, but it keeps the event from propagating up to other handlers.

like image 93
Kevin Avatar answered Oct 13 '22 21:10

Kevin


e.stopImmediatePropagation() is handy if you have no other events firing when you click that specific element. What you should do otherwise is compare the e.currentTarget with the element you want to select. I.e.

events: {
    'click a': 'toggle'
}

toggle: function(e) {
    if (e.currentTarget == this.$el.find('a')[0]) {
        ...
    }
}

That way, if you have a parent view also firing an event when that link is clicked, it won't be stopped by e.stopImmediatePropagation();

like image 22
cjlarose Avatar answered Oct 13 '22 21:10

cjlarose