Search code examples
javascriptjquerydjangodjango-autocomplete-light

When calling jQuery's .trigger() function propagation to other handlers bound to the element stops


When using .trigger() event on element other events bound to this event are not firing. When I comment this line everything goes well. I'm using django-autocomplete-light library so I simplified this example.

<input type="text" class="js-input">
<div class="js-box">
    <!-- code inside the box is loaded dynamically -->
    <a href="#" class="js-autocomplete-item"></a>
</div>

Not working

selectChoice event is fired and.

var boxClickHandler = function(e) {
    var current = this.box.find('.' + this.hilightClass);

    $(".js-input").trigger('selectChoice', [current, this]);
};

$(".js-box").on("mouseclick", ".js-autocomplete-item", $.proxy(boxClickHandler, this));

// somewhere else in the code
$(".js-input").bind('selectChoice', function(e, choice, autocomplete) {
    // empty handler
});

// somewhere else in the code
$(document).on("click", ".js-autocomplete-item", function(e){
    // FIXME: this code is not running
});

Working

var boxClickHandler = function(e) {
    var current = this.box.find('.' + this.hilightClass);

    // $(".js-input").trigger('selectChoice', [current, this]);
};

$(".js-box").on("mouseclick", ".js-autocomplete-item", $.proxy(boxClickHandler, this));

// somewhere else in the code
$(".js-input").bind('selectChoice', function(e, choice, autocomplete) {
    // empty handler
});

// somewhere else in the code
$(document).on("click", ".js-autocomplete-item", function(e){
    // when selectChoice event is not triggered from boxClickHandler this code is running
});

I am a bit confused. I tried many approaches and I believe this is something simple, because this code was running a while ago (before I made an upgrade of django-autocomplete-light lib which uses this code and lots of others in order to run Django 1.8). But it seems like it is just something to do with jQuery. Has anyone had similar problem?


Solution

  • Have you tried opening the "developer tools" or your browser's equivalent to see if any errors are getting triggered by this statement:

    $(".js-input").trigger('selectChoice', [current, this]);
    

    Without a try/catch - any error/exception stops the execution of all following javascript.

    Perhaps try logging this object and/or its properties:

    var inputElement = $(".js-input");