Knockout overriding input value when you haven't specified default value

1,174 views
Skip to first unread message

Naz

unread,
Mar 3, 2011, 5:17:16 AM3/3/11
to knock...@googlegroups.com
I don't know if this is as designed although to me it seems like incorrect behaviour.

When I have inputs rendered with values already set and I don't specify default value on my model when using ko.observable() the value binding removes the current value.

My expected behaviour is knockout would leave those fields intact on initialisation and use them as the default values.

The example of this is http://jsfiddle.net/kr2Gt/20/

The work around is to set the default value in knockout as well, however the issue with this is we prefer to have our JavaScript in separate files and in large forms it means passing lots of parameters from our page to our JavaScript class which I think shouldn't be necessary. 

rpn

unread,
Mar 3, 2011, 9:55:01 AM3/3/11
to knock...@googlegroups.com
Hello- In Knockout your UI reacts to changes in the viewModel and in the best case, your viewModel has no knowledge of or dependency on the actual UI.  In your case though, I can certainly see why it would be preferable to have KO initialize it to the value.

I have a couple of ideas for how you could deal with this in a cleaner way than passing a bunch of parameters.

1- Read the values off of the elements and initialize them before applyBindings is called.  This may be what you are doing already.  This is not really any better than having the page pass a bunch of parameters to you and your javascript would be dependent IDs and structure of the page.  This is useful though when you can't control the HTML that is rendered and want to attach "data-bind" attribtues to them before calling applyBindings.

2- Create a simple custom binding called something like "InitializeValue".  This would only have an init function that would run when the binding is first set up that could set your observable.  Since, the binding would have access to the element and the observable, you would not need to keep track of anything externally.

3- Similar to #2, create a custom binding that is a wrapper to the "value" binding.  The only difference would be that in the init function it will set the observable and then call the normal init function for the "value" binding.  I think that #2 is more explicit and cleaner, but this would save you from having to put two bindings (value and initalize) on the your elements.


Hope this helps.

Naz

unread,
Mar 7, 2011, 5:28:14 AM3/7/11
to knock...@googlegroups.com
Thanks for your help it's been very useful we decided to go with 3rd option we had an issue with a subscribes getting triggered but we overcome that by moving them after the applyBindings and it seems to do the trick.
Reply all
Reply to author
Forward
0 new messages