Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

knockout.js - Using knockout js with jquery ui sliders

I'm trying to figure out if knockout js would work nicely for the following problem:

I have multiple sliders that I want to link to textboxes.

When the textbox is changed the corresponding slider must update to the new value and vice versa.

On changing the slider value or textbox a function needs to be called that uses the input from all textboxes to calculate a result.

I have my quick and dirty jQuery solution here.

Would it be easy to achieve the same result in a more elegant way using knockout js?

I guess I would need to create a custom binding handler like its done in jQuery UI datepicker change event not caught by KnockoutJS

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an example: http://jsfiddle.net/jearles/Dt7Ka/

I use a custom binding to integrate the jquery-ui slider and use Knockout to capture the inputs and calculate the net amount.

--

UI

<h2>Slider Demo</h2>

Savings: <input data-bind="value: savings, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: savings, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>

Spent: <input data-bind="value: spent, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: spent, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>

Net: <span data-bind="text: net"></span>

View Model

ko.bindingHandlers.slider = {
  init: function (element, valueAccessor, allBindingsAccessor) {
    var options = allBindingsAccessor().sliderOptions || {};
    $(element).slider(options);
    $(element).slider({
        "slide": function (event, ui) {
            var observable = valueAccessor();
            observable(ui.value);
        },
        "change": function (event, ui) {
            var observable = valueAccessor();
            observable(ui.value);
        }
    });
    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
        $(element).slider("destroy");
    });
  },
  update: function (element, valueAccessor) {
    var value = ko.unwrap(valueAccessor());
    if (isNaN(value)) {
        value = 0;
    }
    $(element).slider("value", value);
  }
};

var ViewModel = function() {
    var self = this;

    self.savings = ko.observable(10);
    self.spent = ko.observable(5);
    self.net = ko.computed(function() {
        return self.savings() - self.spent();
    });
}

ko.applyBindings(new ViewModel());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...