i want able observe object inside view model. have simple example doesn't work expected, can see problem?
using knockout 1.1.1, have 2 inputs such:
<form data-bind="submit: save"> <input type="text" data-bind="value: deckname" /> <input type="text" data-bind="value: deck().name" /> <button type="submit">go</button> </form>
when page loads, inputs default values, on submitting form viewmodel.deck().name
not updated viewmodel.deckname
is.
<script type="text/javascript"> var initialdata = {"name":"test"}; var viewmodel = { deck: ko.observable(initialdata), deckname: initialdata.name, save: function() { ko.utils.postjson(location.href, { deck: this.deck, deckname: this.deckname }); } }; ko.applybindings(viewmodel); </script>
on form post, deck
still send "test" no matter input whilst deckname
corresponding input value.
what want able observe object viewmodel.deck
, bind properties inputs, properties don't updated.
there several problems have provided.
- you've set 1 time value setter second input since
deck().name
static value (as opposed ko.observable
or ko.observablearray
). (to prove add viewmodel.deck({"name":"updated test"});
end of script after ko.applybindings(viewmodel);
) deckname
1 way binding - it's written during initial applybindings
, viewmodel
updated changes made user or scripts <input>
. however, if make programmatic changes viewmodel
input field not updated match. you'll want take @ last part of knockout.js' value binding documentation.
a improved version:
<form data-bind="submit: save"> <input type="text" data-bind="value: deckname" /> <input type="text" data-bind="value: deck().name" /> <button type="submit">go</button> </form> <script type="text/javascript"> var initialdata = {"name":"test"}; var viewmodel = { deck: ko.observable(initialdata), // set 2 way binding deckname: ko.observable(initialdata.name), // set 1 time value setter save: function() { ko.utils.postjson(location.href, ko.tojson(this)); // when save model post *it* back, rather // serializing hand. } }; ko.applybindings(viewmodel); viewmodel.deck({"name":"updated test"}); </script>
an alternate version using fromjs
:
<form data-bind="submit: save"> <input type="text" data-bind="value: name" /> <button type="submit">go</button> </form> <script type="text/javascript"> var initialdata = {"name":"test"}; var viewmodel = ko.mapping.fromjs(initialdata); viewmodel.save = function() { ko.utils.postjson(location.href, ko.tojson(this)); // when save model post *it* back, rather // serializing hand. } ko.applybindings(viewmodel); </script>
you'll want @ knockout's fromjson
, fromjs
funcitons (implemented in mapping plugin).
Comments
Post a Comment