knockout.js data-bind 'with' conflicts with jQuery change event

data-binding, knockout.js, onchange

Solution

The `with` binding is a wrapper to the `template` binding. It copies off the child elements and uses them as the template. So, if your `detailedStudent` is changing, then KO will be rendering new elements each time that did not have the event handler attached to it.

Some alternatives:

- use a binding to attach the event handler (can use `event` binding)

- create a manual subscription against your `detailedStudent` observable and perform your action in the view model (best option, if your action does not involve DOM manipulation)

- try to use a delegated event handler like jQuerys `$.on()` http://api.jquery.com/on/.

Problem

For some reason, when I use the data-bind="with: detailedStudent" the jQuery change() binding does not get called. I'm dynamically populating the select options but I'm not sure that should matter. This is some of the code I'm using just to try to give a decent picture of what's going on: ``` var viewModel; $(document).ready(function() { viewModel = new StudentViewModel(); ko.applyBindings(viewModel); // this change event is not getting called, but if i put the onchange directly into the html as an attribute, it works fine. $("#accountDialog").find("#mySelect").change(function() { alert('hi'); } } function Student(data) { var self = this; ko.mapping.fromJS(data, {}, this); } function StudentViewModel() { var self = this; this.students = ko.observableArray([]); this.detailedStudent = ko.observable(); } <div id="accountDialog" class="modal hide fade" data-bind="with: detailedStudent"> <select id="mySelect" name="mySelect" data-bind="value: GraduationClassId"></select> </div> ```

Original source