在自定义knockoutjs绑定中更新观察到的模型

时间:2016-11-17 14:35:39

标签: knockout.js

我正在尝试在foreach knockout循环中集成jQuery自动完成扩展。我已经创建了自定义绑定和自动完成功能。但是在自动完成之后我还需要更新可观察的项目模型,并且无法弄清楚如何做到这一点。在这里,你是我的代码:

<!-- ko foreach: items -->
<input data-bind="autoComplete: { source: '/products/item-search-ajax', options: { delay: 100, max: 20, minChars: 2, extraParams: { itcode: 1 }}, findCallback: $parent.findValueCallback }, value: PartNumber" type="text">
<!-- /ko -->

<script type="text/javascript">

        ko.bindingHandlers.autoComplete = {
            init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                var settings = valueAccessor();
                var source = settings.source;
                var options = settings.options;
                var findCallback = settings.findCallback;
                $(element).autocomplete(source, options);
                $(element).result(findCallback);
                ko.bindingHandlers.value.init(element, valueAccessor, allBindings);
            },
            update: function(element, valueAccessor) {
                var value = valueAccessor();
                ko.bindingHandlers.value.update(element,valueAccessor);
            } 
        };

        function QuoteViewModel() {
            var self = this;

            self.items = ko.observableArray(...);

            self.findValueCallback = function(event, data, formatted) {

                // Need to update Item model here from autocomplete
            };
        }

 </script>

1 个答案:

答案 0 :(得分:0)

您基本上可以将$data(在此foreach中将是一个Item模型)对象传递给一个返回处理函数的函数:

self.findValueCallback = function(item) {
    return function(event, data, formatted) {
        //u have access to particular item
    }
}

并在绑定中:findCallback: $parent.findValueCallback($data)