0
votes

I have quite a specific requirement for a custom binding that I'm not sure how to implement.

I want to use the new textInput binding but unfortunately it doesn't play well with a placeholder polyfill I use. I have been using the value binding with valueUpdate on keyup but I like the many edge cases that textInput can also handle.

My requirement here is that in instances where the value equals the value of the placeholder attribute the viewmodel should have an empty string.

Here's a JSBin comparing the current and textInput based methods, open it in a browser like IE8 to see the differences.

Edit

Attempting to re-explain the issue. The problem comes from knockout binding the value of an input field to the viewmodel and the polyfill for an input working by replacing empty input fields with a value equal to the placeholder attribute (pretty much the approach taken by all polyfills for placeholder).

Previously I've been using the value binding and using valueUpdate on the keyUp event. This means that the bound viewmodel property updates as someone types. As the polyfill replaces the value in JS on the blur event the input field will have a value of the placeholder attribute but the viewModel value will still be an empty string.

The textInput binding is more complex but more useful, however the polyfill replacing an empty input value also triggers the knockout update. Due to the complexities and edge cases that textInput handles reusing the old approach of valueUpdate on keyUp is not an option. What I want instead is to create a binding like textInput but is aware of such polyfills.

Basically If I have

<input data-bind="placeholderTextInput:query" type="text" placeholder="Search..."/>

viewModel = {
    query: ko.observable('');
}

The binding should work as normal with the exception that if input.value === input.attribute['placeholder'] then viewModel.query() === ''.

1
I don't understand what you are asking. What do you mean "the viewmodel should have an empty string"? You want to clear the search input when it fits one item? - GôTô
@GôTô hi, is the edit any clearer now? - Chao

1 Answers

0
votes

Ug...

Disclaimer: I don't have easy access to IE8 at the moment...

Best I know of, there is no easy solution to this.

I know of two options:

Option 1: Find a different placeholder fill in

This is the approach I would take. Find something that doesn't actually fill in the text box, but drops another element on top of it.

Option 2: Use a computed

If you are stuck with that particular placeholder library, then you need to create a computed value, call it query2 for now.

In the computation function for query2, have it access the value of query then compare it against the placeholder attribute. If they match, return "", else return query