该applyBindings()的Ajax请求完成之前过快,叫过快、applyBindings、Ajax

2023-09-10 16:25:14 作者:笑靥如花

请考虑以下视图模型片段:

  VAR ID,given1,given2;

$获得(testSynUfGet.aspx,空,功能(数据){
    ID = data.id;
    given1 = data.given1;
    given2 = data.given2;
},'JSON');
//警报('这里');
ko.applyBindings(新视图模型(ID,given1,given2));
 

看来,通过 $我的AJAX调用。获得过慢或 ko.applyBindings()是太快。无论哪种方式,似乎淘汰赛只能正确地绑定,如果我取消注释行警报('这里');

如果我离开它评价说,没有任何控件得到填充。

任何想法,乡亲?

唯一的变通方法我能想到的就是做 .applyBindings 的回调函数的 $一部分。让是这样的:

  $。获得(testSynUfGet.aspx,空,功能(数据){
    ko.applyBindings(新视图模型(data.id,data.given1,data.given2));
},'JSON');
 

解决方案

您的解决方法是做事情的正确方法。这是你的'sucess处理程序被调用时返回的数据,这是正确的点,然后填充您的视图模型和应用绑定。

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'); 

解决方案

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.