Currently, I have a basic implementation that fixes when all images are loaded, but I'm not happy with the code, scalability, and some tight connection between the UI and viewModel.
I have an array from promises that I declared outside my viewModel and bindingHandler so that each of them has access to it. The Handler binding will push each unresolved promise into the array, and the init function will wait until the array receives all the allowed promises. As soon as this happens, a function is called that sets a uniform height for all images.
Here's the user interface:
<ul data-bind="foreach: movies">
<li>
<div class="image">
<img data-bind="imageLoad: { src: posters.Detailed, alt: title }"/>
</div>
</li>
</ul>
Other side:
function ViewModel() {
var self = this;
self.movies = ko.observableArray([]);
self.init = function(data) {
self.isLoading(true);
self.movies = ko.utils.arrayMap(data, function(item) {
return new robot.ko.models.Movie(item);
});
$.when.apply($, promises).done(function () {
robot.utils.setThumbnailHeight($('.thumbnails li'), function () {
self.isLoading(false);
});
});
};
}
ko.bindingHandlers.imageLoad = {
init: function(element, valueAccessor) {
var options = valueAccessor() || {};
var promise = $.Deferred();
var loadHandler = function() { return promise.resolve; };
promises.push(promise);
ko.applyBindingsToNode(element, {
event: { load: loadHandler },
attr: { src: options.src, alt: options.alt }
});
}
}
viewModel bindHandler, , , bindHandler , . - , , , viewModel. data- , , , .
, - .
, , , , , ( ) , Model?