Andrey
Andrey

Reputation: 750

knockout value binding: the way to reread property from html element

I need a way to have KO reload property from html element when using value binding.

The problem is I need to use form.reset() method.

And after using the method knockout observables were not updated because there is no event "reset" for form elements and event "change" is not triggered by browsers.

Since both FF and Chrome do not trigger "change" after form.reset() (at least for input[type=file]), I think may be this is a feature, but I don't understand this anyway.

Anyway, do I have any way to say to knockout that it needs reload values from dom elements?

I would just call something like myViewModel.reload() or myObservable.reload() after myform.reset() and it would solve my problem.

Or may be somebody see another way to solve my problem? Any ideas are wellcome.

Thanks

Upvotes: 1

Views: 920

Answers (1)

Ilya Luzyanin
Ilya Luzyanin

Reputation: 8110

Generally, form reset doesn't generate change events that Knockout could use to update values, see this bug. Although, you can implement manual reset of your fields on form reset event, like this:

ViewModel:

function ViewModel() {
    var self= this;
    self.fileInput = ko.observable();
    self.textInput = ko.observable();
    self.showFileInputValues = function() {
        alert("File input: " + self.fileInput()+"\n Text input: " + self.textInput());
    }
    self.reset = function() {
        self.fileInput(undefined).textInput(undefined);
    }
}

Markup:

<form data-bind="event: { reset: reset }">
    <input type="file" data-bind="value: fileInput" />
    <input type="text" data-bind="value: textInput" />
    <input type="reset" value="Reset form" />
</form>
<button data-bind="click: showFileInputValues" >Show value</button>

See demo.

Another approach is to recreate your form view model instead of cleaning it.

Upvotes: 2

Related Questions