KnockoutJS - Moving ViewModel

I want to switch an object in viewModel with a different one 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 link it to:

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

it works great the first time, but if I link it to another object a second time, the first binding will not go away.

How can I easily switch an object of an object into my view mode?

+8
javascript
source share
1 answer

Basically you want your whole view model to be visible, and then replace the new personViewModel object. It would be like this:

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

Then simply replace the new person as follows:

 viewModel.person(new personViewModel(newPerson)); 
+14
source share

All Articles