durandal knockout - 奇怪的绑定/定时错误?

时间:2013-06-01 12:24:28

标签: durandal

我遇到了一些奇怪的绑定/计时行为 - 我已粘贴相关代码。当我在chrome中手动缓慢地逐步执行代码时,当我让它正常运行时它会正确地填充我的下拉列表它不会....我做错了什么?我已经在控制台输出中输入了“获得省份”的时间不同。

 var provinces = ko.observableArray();

 var vm = {
        activate: activate,
        viewAttached:viewAttached,
        title: 'Home View',
        provinces: provinces,
    };

return vm;

  function activate() {
            getProvinces(provinces);
            return true;
    }

function viewAttached() {
    console.log("got data");
}  

简单的ajax调用如下所示,我传入了我的observable(这几乎完全来自John Papa pluralsight演示):

getProvinces: function (observableArray) {
   observableArray([]);

   var options = {
        url: currentServer + 'regions/GetInUseProvinces',
        type: 'GET',
        async: true,
        dataType: "json",
    };

    $.ajax(options).then(querySucceded);

    function querySucceded(data) {
        var provinces = [];
        data.forEach(function(item) {
            var s = new MedappData.Data.Province(item.Name, item.ID);
            provinces.push(s);
        });
        observableArray(provinces);
        console.log('got provinces');
    }
},  

控制台输出在两者之间的区别如下。

当我将断点放入并手动逐步执行时,我得到以下内容并且它完美地运行:

["Activating", Object]
["[viewmodels/shell] ", "Medapp loaded..."] system.js:62
["Activating Route", Object, Object, n.Object]
["Activating", Object]
["Binding", "views/shell", Object]
got provinces vendor:5319
["Binding", "views/nav", ko.bindingContext]
["Binding", "views/home", Object]
["Binding", "views/footer", ko.bindingContext]
got data

当我删除断点并让它运行时,输出如下,没有任何内容填充。

["Activating", Object]
["[viewmodels/shell] ", "Medapp loaded..."] system.js:62
["Activating Route", Object, Object, n.Object]
["Activating", Object]
["Binding", "views/shell", Object]
["Binding", "views/nav", ko.bindingContext]
["Binding", "views/home", Object]
["Binding", "views/footer", ko.bindingContext]
got provinces vendor:5319
got data 

1 个答案:

答案 0 :(得分:3)

getProvinces是异步操作,因此您必须返回一个承诺,以便让Durandal能够确定何时允许继续撰写。在异步操作后返回true不会这样做。

$.ajax(...已经返回了一个承诺,因此将getProvinces更改为

return $.ajax(options).then(querySucceded);

并在activate

function activate() {
    return getProvinces(provinces);
}

应该做的伎俩。