1

カラー ピッカーとして使用するカスタム バインディングを作成しました。

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

それぞれが他の色を表す 10 個のインライン 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 に答える