YS.
YS.

Reputation: 1828

The applyBindings() is too fast, called before Ajax request completes

Please consider the following ViewModel snippet:

var id, given1, given2;

$.get("testSynUfGet.aspx", null, function (data) {
    id = data.id;
    given1 = data.given1;
    given2 = data.given2;
}, 'json');
//alert('here');
ko.applyBindings(new viewModel(id, given1, given2));

It seems that my ajax call through $.get is too slow or the ko.applyBindings() is too fast. Either way, it seems that knockout can only properly bind if I uncomment the line alert('here');.

If I leave it commented, none of the controls get populated.

Any ideas, folks?

The only work around I could think of is to do .applyBindings as part of the function callback in $.get like this:

$.get("testSynUfGet.aspx", null, function (data) {
    ko.applyBindings(new viewModel(data.id, data.given1, data.given2));
}, 'json'); 

Upvotes: 7

Views: 3169

Answers (3)

Sergey Zwezdin
Sergey Zwezdin

Reputation: 386

More true way is execute your ajax call inside viewmodel object and populate his properties.

Upvotes: 0

Gnurfos
Gnurfos

Reputation: 1010

This workaround will only work as long as you have only one ajax call on the page. I think the right solution is to create your viewmodel first, with id, given1, and given2 being observables (initally empty). And then in the ajax callback, you change the value of those observables.

Upvotes: 8

Mark Robinson
Mark Robinson

Reputation: 13278

Your workaround is the correct way to do things. This is your 'sucess' handler which is called when the data is returned and that is the correct point to then populate your view model and apply the bindings.

Upvotes: 15

Related Questions