Change event on select with knockout binding, how can I know if it is a real change?
Actually you want to find whether the event is triggered by user or program , and its obvious that event will trigger while initialization.
The knockout approach of adding subscription
won't help in all cases, why because in most of the model will be implemented like this
- init the model with undefined data , just structure
(actual KO initilization)
- update the model with initial data
(logical init like load JSON , get data etc)
- User interaction and updates
The actual step that we want to capture is changes in 3, but in second step subscription
will get call ,
So a better way is to add to event change like
<select data-bind="value: level, event:{ change: $parent.permissionChanged}">
and detected the event in permissionChanged
function
this.permissionChanged = function (obj, event) {
if (event.originalEvent) { //user changed
} else { // program changed
}
}
This is just a guess, but I think it's happening because level
is a number. In that case, the value
binding will trigger a change
event to update level
with the string value. You can fix this, therefore, by making sure level
is a string to start with.
Additionally, the more "Knockout" way of doing this is to not use event handlers, but to use observables and subscriptions. Make level
an observable and then add a subscription to it, which will get run whenever level
changes.