简体   繁体   English

KnockoutJS自定义绑定多个颜色选择器

[英]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. 我刚刚开始使用knockoutJS并认为我会通过创建一个改变页面元素颜色的小程序来进行实验。 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. 我正在为颜色选择器使用jquery频谱插件并将其附加到一个小引导输入组插件上,并在输入框旁边显示十六进制颜色。

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': 为了改变颜色,我认为最好的办法是为颜色变化创建一个自定义绑定,它会更新observable,在本例中为'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: 在这里JSFiddle:

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

You are missing the var keyword before your variable declarations: 在变量声明之前,您缺少var关键字:

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

Demo JSFiddle . 演示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... 没有var关键字valuemyColor被声明为全局变量 ,并且在添加第二个绑定处理程序时覆盖了第一个...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM