Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an observable to read the value from the DOM Element

Tags:

I have a hidden 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

like image 900
Hugo Zapata Avatar asked Aug 24 '11 00:08

Hugo Zapata


2 Answers

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.

like image 87
Alex KeySmith Avatar answered Oct 27 '22 19:10

Alex KeySmith


It worked by adding $("hiddenInputId").trigger("change"); for my case without adding a ko binding handlers.

Thanks !

like image 26
Mounir Avatar answered Oct 27 '22 21:10

Mounir