javascriptjqueryknockout.jscustom-binding

KnockoutJS custom binding with multiple color pickers


I'm just starting out with knockoutJS and thought I would experiment by creating a little program that changes the colours of elements on a page. I'm using the jquery spectrum plugin for the color picker and have attached it to a little bootstrap input-group-addon, with the hex colour displaying in the input box alongside.

In order to change the colours, I thought the best thing to do would be to create a custom binding for the colour change, which updates the observable, in this case 'color1':

ko.bindingHandlers.changeColor = {
    init : function(element, valueAccessor){    
        value = valueAccessor();
        myColor = value;

        $(element).spectrum({
            beforeShow: function(color){
                $(this).spectrum("set", $(this).css("background-color"));
            },

            move: function(color){
              myColor(color.toHexString().toUpperCase());   
            }
        });
    }
};

function ColorViewModel(){
    color1 = ko.observable("#FFF000");
}

ko.applyBindings(new ColorViewModel()); 

I've then used the following markup:

<div class="input-group-addon" data-bind="style : {backgroundColor : color1()}, changeColor : color1"></div>
<input type="text" class="form-control input-sm" data-bind="value: color1()" />

This works fine, but my problem comes when attempting to add a second color box associated with a different color observable.

Rather than updating each colour observable individually, each colour picker now only updates the last color observable that was bound. I'm sure I'm missing something pretty obvious or I have misunderstood something with the knockout custom bindings, but would appreciate it if somebody could point out where I'm going wrong.

Here the JSFiddle:

http://jsfiddle.net/mc3fLjq6/1/


Solution

  • You are missing the var keyword before your variable declarations:

    var value = valueAccessor();
    var myColor = value;
    

    Demo JSFiddle.

    Without the var keyword value and myColor are declared as global variables, and you overrode the first one when added the second binding handler...