1

我创建了一个自定义绑定以用作颜色选择器。

<ul data-bind="colorPicker: selcol"></ul>

它创建了 10 个内联 div,每个 div 代表其他颜色。当我单击一个 div 时,颜色被选中。我在分配 'selected; 时遇到问题;选择 div 的 css 类。我尝试在自定义绑定中使用 css 绑定,但这不起作用。它只选择即使在选择其他 div 后仍保持选中状态的初始 div。

请查看示例:http: //jsfiddle.net/zbkkzdsp/Jbvvq/

谢谢你的帮助。如果您对我的代码有任何提示或意见,请告诉我。我是淘汰赛的新手,会抓住任何机会了解更多信息。

4

1 回答 1

3

似乎您在自定义绑定中使用计算值做了很多花哨的事情,所以我建议为您的颜色创建视图模型。

首先为每种颜色定义一个视图模型:

var ColorModel = function(options) {
  var self = this;

  // Keep a reference to the parent picker for selection
  self.picker = options.picker;

  // The CSS value of the color
  self.color = ko.observable(options.color || 'transparent');

  // A flag denoting whether this color is selected
  self.selected = ko.observable(options.selected || false);

  // This will be called when the corresponding color link is clicked
  // Note that we're not doing any event binding with jQuery as with your custom binder
  self.select = function() {
    self.picker.selectColor(self); 
  };
};

然后是颜色选择器本身的视图模型:

var ColorPickerModel = function() {
  var self = this;

  // The list of all colors
  self.colors = ko.observableArray([]);

  self.addColor = function(color) {
    var newColor = new ColorModel({
        picker: self,
        color: color
    });

    self.colors.push(newColor);
    return newColor;
  };

  // Called by individual colors
  self.selectColor = function(colorModel) {
    // Deselect the current color so we don't select two
    var current = self.selected();
    if (current) {
      current.selected(false);
    }

    // Mark the color as selected - KO will do the rest
    colorModel.selected(true);

    // Remember this color as the selected one to deselect later
    self.selected(colorModel);
  };

  // Create at least one default color
  var transparent = self.addColor('transparent');

  // Keep track of the selected color - set to transparent by default
  self.selected = ko.observable(transparent);
  transparent.select();
};

然后将您的 HTML 视图绑定到您的选择器视图模型:

<div id="color-picker">
  <div data-bind="foreach: colors">
    <a href="#" data-bind="
       style: { 'background-color': $data.color }, 
       css: { 'selected': selected }, 
       click: select"></a>
  </div>
  <div>
    Selected color: <span data-bind="text: selected().color"></span>
  </div>    
</div>

并将它们联系在一起:

var pickerDiv = document.getElementById('color-picker'),
    picker = new ColorPickerModel();

// Add some colors
picker.addColor('red');
picker.addColor('blue');
picker.addColor('green');
picker.addColor('orange');
picker.addColor('purple');
picker.addColor('black');

// Bind Knockout
ko.applyBindings(picker, pickerDiv);

// Add more colors - the view will update automatically
picker.addColor('pink');

这是一个工作示例:http: //jsbin.com/izarik/1/edit

于 2013-01-06T02:08:27.237 回答