Jquery color picker binding handler creates multiple divs

前端 未结 2 1683
春和景丽
春和景丽 2020-12-11 10:55

I am trying to use this jquery color picker with knockout.js. I have written custom banding handler to bind colorpicker input control with my viewModel color value.

相关标签:
2条回答
  • 2020-12-11 11:09

    Here is the updated code for jQuery ColorPicker binding handler (to used with knockout.js libraray).

    ko.bindingHandlers.jqColorPicker = {
      init: function (element, valueAccessor, allBindingsAccessor) {
    
        // set default value
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).val(value);
    
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().colorPickerOptions || {};
        $(element).colorPicker(options);
    
        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {            
            var observable = valueAccessor();            
            observable($(element).val());                        
        });
    
        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).colorPicker("destroy");
        });
    
      },
      update: function (element, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).val(value);        
        $(element).change();        
      }
    };
    
    0 讨论(0)
  • 2020-12-11 11:23

    In your update code you're effectively creating new colorpickers.

    When the color changes, the update function is called and there you create a new picker. If you try '$(element).colorPicker("value", value);' in firebug, you will see it's not a setter, but a constructor.

    0 讨论(0)
提交回复
热议问题