How to force an observable to read the value from the DOM Element
I have a hidd开发者_如何学运维en input and bind the value to an observable property of my model. I'm using another plugin that internally updates the value of that hidden input, however the observable doesn't update it's value.
How can i force the observable to update it's value from the element?
something like valueHasMutated but in the other way.
Thanks
I realise you've already come up with a solution.
But I'd thought I'd post my own incase anyone comes across this, as it's up high in the Google results with no answers, so might come in useful for someone.
ko.bindingHandlers.hiddenInputValue = {
init: function (element, valueAccessor) {
$(element).bind("change", function (event, data, formatted) { //hidden vars don't usually have change events, so we trigger $myElement.trigger("change");
var value = valueAccessor();
value($(this).val()); //rather than $(this).val(), might be best to pass our custom info in data
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
$(element).val(value);
}
};
And the html
<input type="hidden" name="myName" id="myId" data-bind="hiddenInputValue: myModelValue" >
Because hidden inputs don't have change events normally, you'll need to trigger your own event when ever you change the value e.g.
$("#myId").trigger("change");
I'm not sure if this is the best solution, but the best I could come with in the timescale I'm working to :-) I might put something into the knockout wiki if I come up with something more elegant.
It worked by adding $("hiddenInputId").trigger("change");
for my case without adding a ko binding handlers.
Thanks !
精彩评论