我认为结合 Isotope 和 Knockout 的最佳选择是通过对后者的绑定。为此,我编写了一个名为Knockout-Isotope 的文章。请注意,它需要Knockout的分叉版本,但希望我所做的微小更改可以在某个时候集成回来。
由于我刚刚完成了 Knockout-Isotope,它没有经过很好的测试,但它至少可以处理我到目前为止所遇到的场景。
代码
演示小提琴。
HTML:
<h1>Knockout Isotope Binding Demo</h1>
<p>This is a demonstration of the
<a href="https://github.com/aknuds1/knockout-isotope">Knockout-Isotope</a>
binding for <a href="http://knockoutjs.com/">Knockout</a>, which visualizes
Knockout observableArrays through
<a href="http://isotope.metafizzy.co/index.html">Isotope</a>.
</p>
<p>Click on an item to remove it or click in the item container to add a new item</p>
<div id="container" data-bind="isotope: { data: items, isotopeOptions: getOptions }, click: addItem">
<div data-bind="text: text, click: $parent.removeItem, clickBubble: false"></div>
</div>
JavaScript:
function ItemModel(parent) {
var value, self = this,
found, i;
for (value = 0; value < parent.items().length; ++value) {
found = false;
for (i in parent.items()) {
var item = parent.items()[i];
if (item.value() == value) {
found = true;
break;
}
}
if (!found) {
break;
}
}
this.value = ko.observable(value);
this.text = ko.computed(function () {
return "Item " + self.value();
});
}
var ViewModel = function () {
var self = this;
self.items = ko.observableArray();
self.items.push(new ItemModel(self));
self.items.push(new ItemModel(self));
this.removeItem = function (item) {
self.items.remove(item);
};
this.addItem = function () {
self.items.push(new ItemModel(self));
};
// Knockout callback for getting Isotope options
this.getOptions = function () {
return {
masonry: {
columnWidth: 210
}
};
};
};
ko.applyBindings(new ViewModel("Test"));