DhiwaTdG DhiwaTdG - 2 months ago 12
Javascript Question

JavaScript bind arguments correctly

I've got the following

bootstrap3
button code which is enclosed inside a container
div
. The button has no text apart from a
plus
icon.

<div id="container">
...
<a type="button" class="btn btn-success input-sm btn-add">
<span class="glyphicon glyphicon-plus-sign black" aria-hidden="true"></span>
</a>
...
</div>


Following is my
JS-Object
with event listener for the
plus
button.

var query_builder = {
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
this.$container = $("#container");
...
},
bindEvents: function() {
this.$container.on('click', '.btn-add', this.addRule.bind(this));
...
},
addRule: function(evt) {
...
...
$(evt.target).addClass('invisible');
}
}



  • When I click anywhere outside
    plus
    icon but within the button, the event gets triggered and at the end it goes invisible.

  • When I click exactly the
    plus
    icon the event gets trigged but only the icon goes invisible leaving the button blank. I don't know how to pass the context of the button correctly when I bind the event.



Note: I'm new to Object Oriented JavaScript.

Answer

Use evt.currentTarget. It's a special jQuery event field that has something to do with event delegation, I think. I wish I had a more solid answer, but I'm glad it worked for you :)

Edit: Here is some documentation.

event.currentTarget

https://api.jquery.com/event.currentTarget/

Description: The current DOM element within the event bubbling phase.

This property will typically be equal to the this of the function.

event.target

https://api.jquery.com/event.target/

Description: The DOM element that initiated the event.

The target property can be the element that registered for the event or a descendant of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.