杜兰达尔与微风的子视图,承诺和激活的问题



我以为我能做到这一点,但我认为我只是幸运地在第一次尝试时快速查找了数据库。第二个返回更多数据并失败。

所以。简单的设置是一个视图和视图模型。让我们称之为view1。

view1.js使用require加载依赖的子视图,子视图1和子视图2。假设子视图1用于显示客户列表,子视图2用于显示产品列表。我把这些放在单独的子视图中,因为它们将在其他需要客户列表或产品列表的页面上的其他地方使用,我不想一直重新创建相同的代码。

两个子视图的结构如下:

define(['services/datacontext'], function (datacontext) {
    var customerList= ko.observableArray();
    var getCustomerList= function () {
        var workingList = [];
        //do some sorting and processing on the customerList array
        //do stuff here
        customerList(workingList);
    };
    var activate = function () {
        //get customers!
        return datacontext.getCustomers(customerList).then(getCustomerList());
    };
    var vm = {
        activate: activate,
        customerList: customerList,
    };
    return vm;
});

在主视图1.js(它被shell.js直接调用,所以activate方法会自动启动)中,我有这样的:

(我的"定义"设置中引用了两个子视图)

var activate = function () {
    subview1.activate(); //set up customers
    subview2.activate(); //set up products
    //do some other datacontext calls for stuff used directly and only in view1
};
//other code in here...
    var vm = {
        activate: activate,
        customerList: subview1.customerList,
        productList: subview2.productList
    };

在view1.html中,我只有标准的敲除绑定,如"foreach:customerList"等。

我的产品列表(1320个产品)中什么都没有,而我的客户列表(66个客户)通常都正常工作。如果我使用chrome调试并逐步完成,在我看来,subview1"activate"方法会很好地启动,因为我在那里有一个停止点。datacontext中的下一个停止点也被击中,但随后出现了错误。在我的数据上下文查询中,我有这样的:

    var getCustomers = function (customersObservable, forceRemote) {
        if (!forceRemote) {
            var p = getLocal('Customers', orderBy.customer);
            if (p.length > 0) {
                customersObservable(p);
                //resolves the promise created when calling getCustomers
                return Q.resolve();
            }
        }
        var query = EntityQuery.from('customer')
            .orderBy(orderBy.customer);
        return manager.executeQuery(query)
            .then(querySucceeded)
            .fail(queryFailed);
        function querySucceeded(data) {
            if (groupsObservable) {
                groupsObservable(data.results);
            }
            log('Retrieved customers from remote data source',
                data, true);
        }
    };

而问题似乎是承诺解决得太早。我在子视图1"getCustomerList"中的停止点在我在"querySuccessed"上设置的停止点之前被击中,该停止点本应在数据上下文"getCustomers"完成后激发。

我在设置中做错了什么吗?从逻辑上讲,这对我来说似乎是正确的,但很明显,我还没有跟上承诺在杜兰达尔的作用/决心,从我的角度来看,有些事情正在以意想不到的顺序发生!我期望的所有数据都会返回,这只是在调用subview1中的"getCustomerList"之后发生的,这是我需要对象以便处理它的地方。在处理运行时,对象中什么都没有,所以我什么都没有显示。

如果希望激活主视图以等待子视图的getCustomers函数完成,则从主activate函数返回promise。

例如

//in view1.js
var activate = function () {
    return $.when(
        subview1.activate(), //set up customers
        subview2.activate() //set up products
    ).then(function(){
        //do some other datacontext calls for stuff used directly and only in view1
    });
};

最新更新