使用Linqjs和Knockout延迟加载

时间:2012-05-08 07:36:19

标签: javascript knockout.js

是否有可能在淘汰数据绑定阶段使用Enumerable? 如果我第一次使用ToArray,我只能使用它,它将使用Enumerable

http://jsfiddle.net/xZmWx/

1 个答案:

答案 0 :(得分:0)

您可以编写自己的foreach变体来使用Enumerables。

ko.bindingHandlers['foreach2'] = {
    makeTemplateValueAccessor: function(valueAccessor) {
        return function() {
            var bindingValue = ko.utils.unwrapObservable(valueAccessor());

            if (bindingValue instanceof Enumerable) {
                bindingValue = bindingValue.ToArray();
            }

            // If bindingValue is the array, just pass it on its own
            if ((!bindingValue) || typeof bindingValue.length == "number")
                return { 'foreach': bindingValue, 'templateEngine': ko.nativeTemplateEngine.instance };

            // If bindingValue.data is the array, preserve all relevant options
            return {
                'foreach': bindingValue['data'],
                'includeDestroyed': bindingValue['includeDestroyed'],
                'afterAdd': bindingValue['afterAdd'],
                'beforeRemove': bindingValue['beforeRemove'],
                'afterRender': bindingValue['afterRender'],
                'templateEngine': ko.nativeTemplateEngine.instance
            };
        };
    },
    'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach2'].makeTemplateValueAccessor(valueAccessor));
    },
    'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach2'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
    }
};

http://jsfiddle.net/madcapnmckay/QeEQg/

希望这有帮助。