0

I wonder if there is any way to update the whole viewmodel with a single object.
For instance, saying our viewmodel is as follows:

    Function ExampleViewModel(){
     this.name = ko.observable();
     this.lastname = ko.observable();
     this.phone = ko.observable();
    }
    var viewmodel = new ViewModel();
    ko.applyBindinings(viewmodel);

And then suppose I create an object like:

    var newObject = {name: "newname", lastname: "lastname", phone: 432}

Instead of setting individually each observable as follows:

        viewmodel.name(newObject.name);
             or
        viewmodel.name(newObject.name).lastname(newObject.lastname) etc etc

Could I update the whole viewmodel doing something like:

        viewmodel.update(newObject)?
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
Santiago Benitez
  • 364
  • 2
  • 12
  • 2
    The mapping plugin can help facilitate that. Though, I think it will still re-render the page for every change as needed. – Jeff Mercado Feb 27 '13 at 21:07

1 Answers1

1

Just loop through the object:

for (var key in newObject) {
    if (viewModel[key] && ko.isObservable(viewModel[key])) {
        viewModel[key](newObject[key]);
    }
}
sroes
  • 14,663
  • 1
  • 53
  • 72
  • You should probably at least check that the property on the `viewModel` is actually an observable. See here: http://stackoverflow.com/questions/9625591/determine-if-an-object-property-is-ko-observable – Matt Burland Feb 27 '13 at 21:11
  • Is there are good reason to go with this rather than use the mapping plugin? – Paul Manzotti Feb 27 '13 at 22:21
  • @SanderRoes Sure, but the mapping plugin would be one line of code! – Paul Manzotti Feb 28 '13 at 09:59
  • Sure you can use the plugin then. But if these are the only requirements, it seems overkill to use a plugin if you can also do it with a few lines of code. – sroes Feb 28 '13 at 10:30