Wednesday, 7 August 2013

Return value from deferred nested function

Return value from deferred nested function

I'm writing a caching function which loads invisible content into the DOM
so that div sizes can be calculated correctly (including images). I am
using jQuery's deferred object to run a function once the caching is
complete.
The problem I am having is I can't work out how to return my props object
once the caching function is complete. The return props at the bottom is
obviously where I want to return my properties object, but it's returning
undefined as the _obj function hasn't completed by the time the return is
called.
My complete function near the bottom is correctly logging the props object
(inc the cacheHeight var), but I can't work out how to return the props
object from the deferred function. I'd like to do something like return
_obj(content).done(complete);, but obviously that returns the deferred
object, not the return from the complete function.
cache : function(content) {
// Vars
var props, ready;
// Deferred switch
var r = $.Deferred();
/*
* Cache object
*/
var _obj = function(content) {
cacheHeight = 0;
ready = false;
cache = document.createElement("div");
cache.style.visibility = "hidden";
$(cache).css("position", "fixed"); // prevents parent's size
being affected
$(cache).append(content);
$(contentWrapper).append(cache);
children = $(cache).children();
// Image loader
var imgs = $(cache).find('img'),
img_length = imgs.length,
img_load_cntr = 0;
if (img_length) { //if the $img_container contains new images.
imgs.on('load', function() { //then we avoid the callback
until images are loaded
img_load_cntr++;
if (img_load_cntr == img_length) {
remaining = children.length;
$.each(children, function(index, value) {
--remaining;
cacheHeight = cacheHeight +
parseInt($(value).outerHeight(false));
if (remaining == 0) {
props = {
height : cacheHeight
}
r.resolve();
}
});
}
});
}
return r;
};
/*
* Return cached object data
*/
var complete = function () {
ready = true;
};
// Resolve when finished
_obj(content).done(complete);
// Return?!?!
return props;
}

No comments:

Post a Comment