Setting objct literal property value via asynchronous callback.
Posted
by
typeof
on Stack Overflow
See other posts from Stack Overflow
or by typeof
Published on 2010-12-23T20:17:14Z
Indexed on
2010/12/23
20:54 UTC
Read the original article
Hit count: 254
JavaScript
|object-literal
I'm creating a self-contained javascript utility object that detects advanced browser features. Ideally, my object would look something like this:
Support = {
borderRadius : false, // values returned by functions
gradient : false, // i am defining
dataURI : true
};
My current problem deals with some code I'm adapting from Weston Ruter's site which detects dataURI support. It attempts to use javascript to create an image with a dataURI source, and uses onload/onerror callbacks to check the width/height. Since onload is asynchronous, I lose my scope and returning true/false does not assign true/false to my object.
Here is my attempt:
Support = {
...
dataURI : function(prop) {
prop = prop; // keeps in closure for callback
var data = new Image();
data.onload = data.onerror = function(){
if(this.width != 1 || this.height != 1) {
that = false;
}
that = true;
}
data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
return -1;
}(this)
};
I'm executing the anonymous function immediately, passing this (which I hoped was a reference to Support.dataURI), but unfortunately references the window object -- so the value is always -1. I can get it to work by using an externally defined function to assign the value after the Support object is created... but I don't think it's very clean that way. Is there a way for it to be self-contained? Can the object literal's function reference the property it's assigned to?
© Stack Overflow or respective owner