看起來你正在用自定義綁定中的計算值做很多花哨的東西,所以我會建議爲你的顏色創建視圖模型。
首先定義爲每個顏色的視圖模型:
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
我沒有看到在撥弄任何代碼,只是結果。任何想法是什麼? –
Jsfiddle這些天很有趣。同時使用http://codepen.io/。 – jjperezaguinaga
是的,即使是最簡單的小提琴,我也遇到了麻煩。結束使用jsbin.com –