Question

I have some event delegation working great on inputs that performs some tasks with:

$("#myParentWrapperId").delegate("input,textarea,select", 'change keypress', function (e) {
 //runStuff();
});

<select data-bind="value:MyVM.MyPropValue"></select>

Down in another method, I'm updating the viewmodel programatically for some of the same input fields.

self.MyListItems()[idx].MyVM.MyPropValue(data.MyVM.MyPropValue);

The problem is when I update the viewmodel programatically for a select field, it seems to also be firing the change event and triggers the above event delegation which I don't want.

Is it possible to either:

A) still update the viewmodel but have it not fire the onchange event for the select, but without breaking the dependent observables?

or

B) in the event delegation above to sniff out and differentiate between when a user causes an onchange event and when the viewmodel update causes the onchange event?

Was it helpful?

Solution

A) still update the viewmodel but have it not fire the onchange event for the select, but without breaking the dependent observables?

From the Knockout documentation: "If you try to set a model value that can't be represented in an already-populated dropdown, reject that change, because you're not allowed to have a model value that disagrees with a visible UI selection." This comment appears right before it fires a change event in the value handler.

So there are two possibilities for why you'll get a change event from a programmatic viewmodel update:

  1. You are setting a value that doesn't exist in the drop-down list. If this is the case, you can add code to check if the value is valid before setting it.

  2. You are setting the value as a numeric type, although the values of the items in the drop-down list are strings. Although Knockout will select the matching item, it fires the change event to signal that the observable needs to be updated to the matching string value. If this is the case, you can make sure you convert the value to a string when setting the observable.

B) in the event delegation above to sniff out and differentiate between when a user causes an onchange event and when the viewmodel update causes the onchange event?

I haven't been able to determine which browsers support this, but the event may have an isTrusted property that you can check. Reference: http://www.w3.org/TR/DOM-Level-3-Events/#h3_trusted-events

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top