Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js - Prevent change event binding to trigger when setting the value through the observable

Tags:

I have a DropDownList with the following bindings:

<select data-bind="value: DropDownValue, event: { change: OnChange }">
    <option value="1">Val 1</option>
    /* and more */
</select>

The OnChange event is fired correctly when the user select a different value from the DropDownList.

The event is also fired when updating the value of the observable property using viewModel.DropDownValue(1).

What I'm trying to achieve, is to trigger the change event ONLY when the user sets the value through the UI.

Is it possible to block the change event when updating the value through the observable?

This is the JSFiddle example: https://jsfiddle.net/5ex5j7jL/3/

like image 606
crushjz Avatar asked Apr 05 '16 13:04

crushjz


1 Answers

Looks like one way to do it is to use the isTrusted property of the event object (true when the event was generated by a user action, false when generated by a script):

self.OnChange = function(viewModel, event) {
  if(event.isTrusted) {
    console.log("from dropdown");
    return;
  } else {
    console.log("NOT from dropdown");
    // do something
  }
};

See updated fiddle

EDIT

Of course, you have to implement some king of mechanism if you want to prevent the user from changing the dropdown via the UI:

function ViewModel() {

    var self = this;

    self.DropDownValue = ko.observable();
    self._original = null;

    self.OnChange = function(viewModel, event) {
      if(event.isTrusted) {
        // rollback the viewModel value to the old one
        viewModel.DropDownValue(self._original)
        return false
      } else {
        // keep a reference to the latest value for later rollback
        self._original = ko.unwrap(viewModel.DropDownValue)
      }
    };
};

See this updated fiddle

like image 93
cl3m Avatar answered Sep 28 '22 01:09

cl3m