Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'); 
like image 255
YS. Avatar asked Sep 15 '11 07:09

YS.


2 Answers

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.

like image 93
Mark Robinson Avatar answered Oct 14 '22 03:10

Mark Robinson


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.

like image 32
Gnurfos Avatar answered Oct 14 '22 05:10

Gnurfos