view raw
DhiwaTdG DhiwaTdG - 7 months ago 40
Javascript Question

JavaScript bind arguments correctly

I've got the following

button code which is enclosed inside a container
. The button has no text apart from a

<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>

Following is my
with event listener for the

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

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

  • When I click exactly the
    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.


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.


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

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

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