JSFiddle - React, Tailwind, and code Playground
by manzanotti
HTML
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.debug.js"></script>
<ul data-bind="foreach: images">
<li data-bind="createImage: $data"></li>
</ul>
JavaScript
var viewModel = function () {
var self = this;
self.Images = [];
self.images = ko.observableArray([]);
self.populate = function () {
var child = new imageVM('Name 1', true);
self.images.push(child);
self.images.push(new imageVM('Name 2', false));
self.images.push(new imageVM('Name 3', true));
self.images.push(new imageVM('Name 4', false));
self.images.push(new imageVM('Name 5', true));
};
};
var imageVM = function (name, flipped) {
var self = this;
self.flipped = ko.observable(flipped);
var origString = 'http://www.fillmurray.com/200/300';
var flippedString = 'http://www.fillmurray.com/300/200';
self.Name = ko.observable(name);
self.imgSrc = ko.computed(function () {
return self.flipped() ? flippedString : origString;
});
};
ko.bindingHandlers.createImage = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// Use something unique to identify this image object
var imageName = viewModel.Name();
var parent = bindingContext.$parent;
var imageObject = parent.Images[imageName];
if (imageObject) {
$(element).empty()
imageObject = null;
}
imageObject = $(element).append('<img src="' + viewModel.imgSrc() + '" />')[0];
parent.Images[imageName] = imageObject;
}
};
$(function () {
var vm = new viewModel();
vm.populate();
ko.applyBindings(vm);
setInterval(function () {
ko.utils.arrayForEach(vm.images(), function (item) {
item.flipped(!item.flipped());
});
}, 300);
});