So I created a binding that handles loading images asychroniously and I wanted to have a spinner to load while it's waiting. Initially I came up with something like this:
ko.bindingHandlers.asyncImgs = {
init: function (element, valueAccessor) {
$(element).spin();
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$(element).spin(false);
ko.bindingHandlers.foreach.update(element.firstElementChild, valueAccessor);
}
}
}
And my html looks like this:
<div class="gifts" style="height: 220px; border: 1px solid" data-bind="asyncImgs: offer_${standardProduct.productIdIndirect}_gifts" data-for="${standardProduct.productIdIndirect}">
<div class="gift" data-bind="foreach: $data">
<img data-bind="attr: {src: image}"/>
<span data-bind="text: description"/>
</div>
</div>
But the above doesn't work! The reason for this is because of the fact that we're not passing in the full context that the foreach binding needs.
To fix it and to get it working, I had to pass in the following params (note this is only for v2.0.0+ of Knockout).
ko.bindingHandlers.asyncImgs = {
init: function (element, valueAccessor) {
$(element).spin();
},
update: function (element, valueAccessor, allBindings, viewModel, context) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$(element).spin(false);
ko.bindingHandlers.foreach.update(element.firstElementChild, valueAccessor, allBindings, viewModel, context);
}
}
};
No comments:
Post a Comment