Maciej Pszczolinski
Maciej Pszczolinski

Reputation: 1968

Knockout Mapping - rebind data after JSON loads

I'm using Knockout with mapping plugin.
I have got problem with initializing page BEFORE server return JSON data.

Everything works fine in scenario:
1. get JSON
2. perform VM = ko.mapping.fromJS(result);
3. perform ko.applyBinding(VM);

however if JSON takes some time to return (e.g. 10 seconds) my page needs to be initialized before json is returned. But if I make ko.applyBinding(VM); with empty VM (let say VM = {};) than call for JSON, and then rebind it again - it won't work.

So my question is - how to rebind model with knockout? I don't want to change value of single observable, but to rebind entire VM (view model) because structure of my data needs to be mapped from JSON - and it is not known before JSON is returned.

Upvotes: 4

Views: 1814

Answers (1)

Matthew Schinckel
Matthew Schinckel

Reputation: 35619

I believe the problem you are describing is that things will not render (and will actually give an error) in your template immediately, and that error prevents the redraw when the data from the server arrives.

If that is the case, the way I generally handle this is to have an observable that knows when the data has been loaded, and the wrap the problematic template code in an if based on this observable.

Update: it is more likely that you are replacing the value of VM. This is no longer the object that is bound to the interface elements.

You can just use the alternate form of the ko.mapping.fromJS call.

ko.mapping.fromJS(result, {}, VM);

Upvotes: 4

Related Questions