2012-09-13 70 views
2

我想用knockout.js來使用這個jquery color picker。我寫了自定義帶綁定處理程序綁定colorpicker輸入控件與我的viewModel顏色值。jquery顏色選擇器綁定處理程序創建多個div

這裏是結合處理程序代碼:

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

    //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).colorPicker("value")); 
    }); 

    //handle disposal (if KO removes by the template binding) 
    ko.utils.domNodeDisposal.addDisposeCallback(element, function() { 
     $(element).colorPicker("destroy"); 
    }); 

}, 
update: function (element, valueAccessor) { 
    var value = ko.utils.unwrapObservable(valueAccessor());  
    $(element).colorPicker("value", value);   
} 

和HTML:

<input type="text" data-bind="colorPicker: newEvent().color, colorPickerOptions: { value:newEvent().color }"/> 

問題是,當我改變顏色它創建的多個div每當我改變顏色時,如圖在圖像中。在我的代碼

enter image description here

誰能請identiy什麼問題?

+1

什麼是'newEvent'?你能提供一個小提琴這個問題的細節嗎? – jimmym715

回答

4

以下是jQuery ColorPicker綁定處理程序的更新代碼(與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

在您的更新代碼中,您正在有效地創建新的顏色選擇器。

當顏色改變時,更新函數被調用,並在那裏創建一個新的選擇器。如果您嘗試'$(element).colorPicker(「value」,value);'在firebug中,你會發現它不是一個setter,而是一個構造函數。

+0

我想使用這個,但不能設置文本顏色,請參閱小提琴:http://jsfiddle.net/AsleG/hmLbb9c0/2/ –