MikeC
MikeC

Reputation: 284

Knockout value binding not updating when jquery off/on used to remove handler

I have a situation where i have a dropdown list bound using knockout:

<select id="RoleGroups" class="tableDropDown" data-bind="options: userGroups, 
                                                         optionsText: 'group_nm',
                                                         optionsValue: 'group_cd',
                                                         value: selectedRoleGroup">
</select>

I have a change handler set on the dropdown:

self.roleGroupChanged = function() {
       //do stuff                    
    return true;
};

When i update the observable array of the dropdown i reset the current selectedRoleGroup observable to a default. I want to prevent the roleGroupChanged handler from firing in this case so i do the following:

$('.tableDropDown').off('change');

//do stuff...set the dropdown value

$('#RoleGroups').on('change', self.roleGroupChanged);

The problem i am running into is that the observable value selectedRoleGroup is now not being updated when the dropdown changes. I can use jquery to get the current value but that defeats the purpose of using knockout. If i remove the code that uses jquery's off and on methods everything works as expected but the handler fires as a result which is not what i want. Looking for ideas what i am doing wrong.

Upvotes: 0

Views: 142

Answers (2)

MikeC
MikeC

Reputation: 284

Figured it out so thought i would post....apparently just doing a .off('change') removes more than just my roleGroupChanged handler. If i do a .off('change', self.roleGroupChanged) or if i had namespaced my handler when i ran .on('change.mystuff', self.roleGroupChanged) and followed it up with a .off('change.mystuff') or .off('.mystuff') everything works as expected.

Upvotes: 0

rwisch45
rwisch45

Reputation: 3702

Instead of using the jQuery events directly, you could tap into the change event in your data-binding. If you use a simple true/false observable for tracking when you are updating your observable array, you can use preventDefault() on the event args for the change event. See updated fiddle

Upvotes: 1

Related Questions