Ahmad
Ahmad

Reputation: 2190

Event handler unbinded after first click

In Backbone marionette composite view, I am using following code .

events: {
        'click th': 'doSort',
        'click #selectAllGroups': 'allMembersSelected'
    },

    allMembersSelected: function(event) {
        var selectAll;
        if ($("#selectAllGroups").prop('checked') == true) {
            selectAll = true;
        } else {
            selectAll = false;
        }

        var allCheckboxes = document.getElementsByName("selectGroupCheckBox");
        for (var i = 0, n = allCheckboxes.length; i < n; i++) {
            allCheckboxes[i].checked = selectAll;
        }


    },

where #selectAllGroups is actually checkbox to select and unselect all checkboxes in the list. the function allMembersSelected is called only first time when the checkbox is clicked , it wouldn't be called on any subsequent clicks. One Interesting point is that If I remove the below section from code, the click handler would be called on subsequent clicks and the issue wouldn't come.

if ($("#selectAllGroups").prop('checked') == true) {
    selectAll = true;
} else {
    selectAll = false;
}

Upvotes: 0

Views: 51

Answers (1)

Jai
Jai

Reputation: 74738

You can update this function as:

allMembersSelected: function(event) {
   event.stopPropagation(); // add this one too, as seems event is bubbling up.
   $('input[type="checkbox"][name="selectGroupCheckBox"]')
                      .prop('checked', $("#selectAllGroups").prop('checked'));

}, 

It will mark check all the checkboxes named "selectGroupCheckBox" only when #selectAllGroups checkbox is checked.


This code block:

events: {
    'click th': 'doSort', // 2. when event comes here all the elements on the row gets replaced by new rows. 
    'click #selectAllGroups': 'allMembersSelected' // 1. click on it bubbles up to the parent th
},

I find it that when you click on th it sorts all the rows and replaces all the elements with the new ones. So all the child elements inside every th if they have any event bound on it that will bubble up to the dom and that would cause in sort.

Same thing is happening with your #selectAllGroups checkbox as it is in the th or i would say that should be in the th so any event bound on it bubbles up to the th which causes in sorting and it feels that event is not working on checkbox but it does.

Upvotes: 1

Related Questions