Handle IE 9 & 10's clear button with Knockout

2020-08-17 02:58发布

问题:

I have an input text box bound to a knockout js observable.

<input id="searchTextBox" class="searchTextBox" type="text" maxlength="25"
       title="Search" placeholder="Search"
       data-bind="value: GridVm.FilterText,
       valueUpdate: 'afterkeydown',
       disable: GridVm.Data().length == 0" />

The problem is that the FilterText observable doesn't update when the user clicks the x in IE.

I've found that I can remove the x (see the screen shot in the linked question), but that's a last resort (I like the feature). This forum says there is no event fired when the x is clicked.

Is there an event that I can use to force a Knockout observable update or a good way to do this in Knockout?

回答1:

If you just change

valueUpdate: 'afterkeydown'

to

valueUpdate: 'input'

it hooks that event to trigger the value update. It's better overall because it also handles clipboard-based actions and text drag-drop actions.



回答2:

I figured it out using the input event and Knockout's event binding. Here is my JsFiddle showing the solution with the code below.

<input type="search" id="input1" data-bind="value: textForBox, valueUpdate: 'afterkeydown',
  event: { input: cleared }" />
var vm = {
    textForBox: ko.observable(),
    cleared: function (data, event) {
        if (event.currentTarget.value === '') {
           this.textForBox('');
        }
    }
};
ko.applyBindings(vm);