从jQuery滑块控件中获取knockout计算的observable

时间:2013-02-19 21:53:15

标签: javascript knockout.js

我有一个用于jQuery滑块控件的自定义挖空活页夹。滑块正在更新currentPage observable,但依赖于currentPage()的泛型ko.computed永远不会触发。 为什么会这样,以及如何解决这个问题,以便触发泛型?

我发现这种技术可以在这里使用asout ajax调用... Asynchronous Dependent Observables。显然,dependentObservable已被computed取代。我能够将其与dependentObservablecomputed.deferEvaluation=false一起使用,但我需要deferEvaluation=true,因此多次触发ajax调用。

小提琴 http://jsfiddle.net/jeljeljel/3WN6v/

HTML

<div style="margin:10px;" data-bind="slider: currentPage, sliderOptions: {min: 0, max: 10, range: 'min'}"></div>

<div id="plugin" data-bind="template: { name: 'template1', data: $data }" ></div>

<script type="text/html" id="template1">
        <span data-bind="text: displayText"></span>
</script>

的Javascript

// create ko custom binding handler for slider control
ko.bindingHandlers.slider = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = ko.toJS(allBindingsAccessor().sliderOptions) || {};
        $(element).slider(options);
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).slider('destroy');
        });
        ko.utils.registerEventHandler(element, 'slidechange', function (event, ui) {
            var observable = valueAccessor();
            observable(ui.value);
        });
    }
};

function DataModel() {
    var self = this;
    self.currentPage = ko.observable(0);
    self.displayText = ko.observable(0);

    ko.computed({
        read: function () {
            $.ajax({
                url: '/echo/json/',
                //data: { page: currentPage() },
                success: function(){
                    self.displayText(currentPage());
                }
            });
        },
        deferEvaluation: true
    });
}

dataModel = new DataModel();
ko.applyBindings(dataModel);

1 个答案:

答案 0 :(得分:1)

您实际上并未在滑块更改事件中更新displayText,因为您要发送到绑定事件的valueAccessor是您绑定到滑块的属性,即currentPage。更改自定义绑定的签名以包含viewModel,然后使用它来更新displayText的值:

// create ko custom binding handler for slider control
ko.bindingHandlers.slider = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = ko.toJS(allBindingsAccessor().sliderOptions) || {};
        $(element).slider(options);
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).slider('destroy');
        });
        ko.utils.registerEventHandler(element, 'slidechange', function (event, ui) {
            viewModel.displayText(ui.value);
        });
    }
};