Knockoutjs,jquery 移动滑块

发布于 2024-12-04 15:13:12 字数 1346 浏览 0 评论 0原文

我想知道是否有人有一个带有 knockoutjs 的 JQM slider 的工作示例。我有两个问题:

1)将值绑定到可观察值 - 我可以最初绑定它,即设置滑块的“值”,但这在拖动时不会更新底层可观察值 - 我认为这与 JQM 放置有关元素过来代表输入吗?

2)更改min、max、value属性时刷新样式。

这是我所拥有的内容的子集,currentItems 根据选择进行更改:

workloadViewModel.filterValues = ko.dependentObservable(function () {
var tmp = {};
var itms = this.currentItems();

if (itms.length == 0) return;

tmp.max = itms[0].val;
tmp.min = itms[itms.length - 1].val;
tmp.minRange = this.minRange();

return tmp;
}, workloadViewModel);


ko.bindingHandlers.jqmRefreshSlider = {
update: function (element, valueAccessor) {
    ko.utils.unwrapObservable(valueAccessor()); //just to create a dependency
    try {
        $("input[type=range]").slider("refresh");            
    } catch (error) {
        trace("error refreshing slider");
    }
}
};

<div id="filters" data-bind="template: {name: 'filterTemplate', data: filterValues}, jqmRefreshSlider: filterValues"></div>

<script id='filterTemplate' type='text/html'>        

    <p>min: ${minRange}</p>
    <p>min: ${min}</p>
    <p>max: ${max}</p>
    <div>
        <input type="range" name="slider_min" id="slider_min" value="${minRange}" min="${min}" max="${max}" />
    </div>
</script>

非常感谢您可以给我的任何帮助。

J

I was wondering if someone had a working example of JQM slider with knockoutjs. I have 2 issues:

1) binding the value to an observable - I can bind it initially i.e. set the "value" of the slider, but this does not update the underlying observable when dragged - I think that this is to do with JQM putting elements over the input to represent it?

2) refreshing the style when changing the min, max, value properties.

Here is a subset of what I have, currentItems changes based on a selection:

workloadViewModel.filterValues = ko.dependentObservable(function () {
var tmp = {};
var itms = this.currentItems();

if (itms.length == 0) return;

tmp.max = itms[0].val;
tmp.min = itms[itms.length - 1].val;
tmp.minRange = this.minRange();

return tmp;
}, workloadViewModel);


ko.bindingHandlers.jqmRefreshSlider = {
update: function (element, valueAccessor) {
    ko.utils.unwrapObservable(valueAccessor()); //just to create a dependency
    try {
        $("input[type=range]").slider("refresh");            
    } catch (error) {
        trace("error refreshing slider");
    }
}
};

<div id="filters" data-bind="template: {name: 'filterTemplate', data: filterValues}, jqmRefreshSlider: filterValues"></div>

<script id='filterTemplate' type='text/html'>        

    <p>min: ${minRange}</p>
    <p>min: ${min}</p>
    <p>max: ${max}</p>
    <div>
        <input type="range" name="slider_min" id="slider_min" value="${minRange}" min="${min}" max="${max}" />
    </div>
</script>

Thanks you very much for any help you can give me.

J

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深海蓝天 2024-12-11 15:13:12

这是绑定到 silver 的工作:

ko.bindingHandlers.slider = {
    init: function (element, valueAccessor) {
        var val = valueAccessor()();
        $(element).slider(
                            {
                                value: val,
                                step: 3,
                                slide: function (event, ui) {
                                    valueAccessor()(ui.value);
                                }
                            });
    },
    update: function (element, valueAccessor) {
        $(element).slider("option", "value", valueAccessor()());
    }
};

This is working binding to silder:

ko.bindingHandlers.slider = {
    init: function (element, valueAccessor) {
        var val = valueAccessor()();
        $(element).slider(
                            {
                                value: val,
                                step: 3,
                                slide: function (event, ui) {
                                    valueAccessor()(ui.value);
                                }
                            });
    },
    update: function (element, valueAccessor) {
        $(element).slider("option", "value", valueAccessor()());
    }
};
笑着哭最痛 2024-12-11 15:13:12

以上都不适合我,因为我的滑块是动态添加的

<html>
 <head>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
 </head>
 <body>
  <span data-bind="text: test"></span>
  <br />
  <br />
  <div class="c-slider" >
  <!-- ko if: is -->
   <input id="test-i" type="range" min="1" max="10" data-bind="value: test, slider: test" />
  <!-- /ko -->

  </div>
  <input id="test-t" type="text"  data-bind="value: test" />
  <script type="text/javascript">

   function model() {
    var self = this;
    self.test = ko.observable("1");
    self.test.subscribe(function(v) {
    alert('s');
    $("#test-i").val(v).slider('refresh');
 });
self.is = ko.observable(true);
 }

 ko.bindingHandlers.slider = {
  init: function(element, valueAccessor) {
   var value = valueAccessor();
   $(document).on({
    "mouseup touchend": function (elem) {
     value($('#' + element.id).val());
    }
   }, ".c-slider");
  }
 };

 var m = new model();
 ko.applyBindings(m);
</script>
 </body>
</html>

none of the above worked for me because my slider was being added dynamically

<html>
 <head>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
 </head>
 <body>
  <span data-bind="text: test"></span>
  <br />
  <br />
  <div class="c-slider" >
  <!-- ko if: is -->
   <input id="test-i" type="range" min="1" max="10" data-bind="value: test, slider: test" />
  <!-- /ko -->

  </div>
  <input id="test-t" type="text"  data-bind="value: test" />
  <script type="text/javascript">

   function model() {
    var self = this;
    self.test = ko.observable("1");
    self.test.subscribe(function(v) {
    alert('s');
    $("#test-i").val(v).slider('refresh');
 });
self.is = ko.observable(true);
 }

 ko.bindingHandlers.slider = {
  init: function(element, valueAccessor) {
   var value = valueAccessor();
   $(document).on({
    "mouseup touchend": function (elem) {
     value($('#' + element.id).val());
    }
   }, ".c-slider");
  }
 };

 var m = new model();
 ko.applyBindings(m);
</script>
 </body>
</html>
深居我梦 2024-12-11 15:13:12

我对 JQM 滑块咬牙切齿了几天。最后,我能够获得真正的双向绑定到滑块值的可观察值,并让它更新拇指滑块和数字范围输入。以下是我的想法:

ko.bindingHandlers.slider = {
    init: function (element, valueAccessor) {
        // use setTimeout with 0 to run this after Knockout is done
        setTimeout(function () {
            // $(element) doesn't work as that has been removed from the DOM
            var curSlider = $('#' + element.id);
            // helper function that updates the slider and refreshes the thumb location
            function setSliderValue(newValue) {
                curSlider.val(newValue).slider('refresh');
            }
            // subscribe to the bound observable and update the slider when it changes
            valueAccessor().subscribe(setSliderValue);
            // set up the initial value, which of course is NOT stored in curSlider, but the original element :\
            setSliderValue($(element).val());
            // subscribe to the slider's change event and update the bound observable
            curSlider.bind('change', function () {
                valueAccessor()(curSlider.val());
            });
        }, 0);
    }
};

以下是它在 HTML 中的使用方式:

<input type="range" data-bind="value: currentLineWidth, slider: currentLineWidth" name="penSizeSlider" id="penSizeSlider" min="1" max="150" />

我也用此信息更新了我的博客。有关集成 Knockout 和 JQuery Mobile 的更多信息可以在那里找到。
http://www.programico.com/1/post /2012/12/knockoutjs-jquerymobile-slider.html

I was gnashing my teeth for a couple days with the JQM slider. Finally I was able to get true 2-way binding to an observable for the slider's value, and have it update both the thumb slider and the numeric range input. Here is what I came up with:

ko.bindingHandlers.slider = {
    init: function (element, valueAccessor) {
        // use setTimeout with 0 to run this after Knockout is done
        setTimeout(function () {
            // $(element) doesn't work as that has been removed from the DOM
            var curSlider = $('#' + element.id);
            // helper function that updates the slider and refreshes the thumb location
            function setSliderValue(newValue) {
                curSlider.val(newValue).slider('refresh');
            }
            // subscribe to the bound observable and update the slider when it changes
            valueAccessor().subscribe(setSliderValue);
            // set up the initial value, which of course is NOT stored in curSlider, but the original element :\
            setSliderValue($(element).val());
            // subscribe to the slider's change event and update the bound observable
            curSlider.bind('change', function () {
                valueAccessor()(curSlider.val());
            });
        }, 0);
    }
};

And here is how it is used in the HTML:

<input type="range" data-bind="value: currentLineWidth, slider: currentLineWidth" name="penSizeSlider" id="penSizeSlider" min="1" max="150" />

I have updated my Blog with this information as well. More info about integrating Knockout and JQuery Mobile can be found there.
http://www.programico.com/1/post/2012/12/knockoutjs-jquerymobile-slider.html

请爱~陌生人 2024-12-11 15:13:12

以下内容对我有用。它还处理动态创建的元素。不过这有点老套。我重用了 Knockoutjs (版本2.1.0): 将布尔值绑定到选择框,用于自动处理将字符串解析为布尔值,反之亦然:

ko.bindingHandlers.jqmFlip = {
    init: function(element, valueAccessor, allBindingsAccessor) {

        var observable = valueAccessor(),
            interceptor = ko.computed({
                read: function() {
                    return observable().toString();
                },
                write: function(newValue) {
                    observable(newValue === "true");
                }
            });

        var result = ko.applyBindingsToNode(element, { value: interceptor });

        try {
            $(element).slider("refresh");
        } catch(x) {

            $(element).next('.ui-slider').remove();
            $(element).slider();
            /*console.log('jqmFlip init error ' + x);*/
        }
        return result;
    },
    update: function (element, valueAccessor) {

        ko.bindingHandlers.value.update.apply(this, arguments);
        var value = valueAccessor();
        var valueUnwrapped = ko.utils.unwrapObservable(value);
        try {
            $(element).slider("refresh");
        } catch(x) {
            debugger;
            console.log('jqmFlip update error ' + x);
        }
    }
};

The following worked for me. It also handles dynamically created elements. It's a bit hacky though. I've reused some code from Knockoutjs (version 2.1.0): bind boolean value to select box for autotically handling parsing strings to bools and vice versa:

ko.bindingHandlers.jqmFlip = {
    init: function(element, valueAccessor, allBindingsAccessor) {

        var observable = valueAccessor(),
            interceptor = ko.computed({
                read: function() {
                    return observable().toString();
                },
                write: function(newValue) {
                    observable(newValue === "true");
                }
            });

        var result = ko.applyBindingsToNode(element, { value: interceptor });

        try {
            $(element).slider("refresh");
        } catch(x) {

            $(element).next('.ui-slider').remove();
            $(element).slider();
            /*console.log('jqmFlip init error ' + x);*/
        }
        return result;
    },
    update: function (element, valueAccessor) {

        ko.bindingHandlers.value.update.apply(this, arguments);
        var value = valueAccessor();
        var valueUnwrapped = ko.utils.unwrapObservable(value);
        try {
            $(element).slider("refresh");
        } catch(x) {
            debugger;
            console.log('jqmFlip update error ' + x);
        }
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文