Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS - Rebinding ViewModel

I want to switch a object in a viewModel with an other, with the same type (e.g Person). If i do this:

var personViewModel = function (person) {
  var self = this;

  self.id = person.id;
  self.firstName = ko.observable(person.firstName);
  self.lastName = ko.observable(person.lastName);
  self.addresses = ko.observableArray(contact.addresses);

  self.removeAddress = function (address) {
  self.addresses.remove(address);
 }
}

and bind it with:

ko.applyBindings(new personViewModel(person), $("#person")[0]);

it works great on the first time, but if i bind it with a other object on a second time, the first binding will not disappear.

How can i switch easily the object person in my viewModel?

like image 421
G Meile Avatar asked Mar 24 '12 18:03

G Meile


1 Answers

You would basically want your entire view model to be observable, then swap in a new personViewModel object. Would be like:

var viewModel = {
  person: ko.observable()
};

viewModel.person(new personViewModel(person));

ko.applyBindings(viewModel);

Then, just swap a new person in like:

viewModel.person(new personViewModel(newPerson));
like image 174
RP Niemeyer Avatar answered Oct 26 '22 23:10

RP Niemeyer