Tuesday, December 25, 2018

javascript - Watch for a property creation event?



I need to be able to determine when an object is created (not a DOM element -- a javascript object).



An answer to this question has some very useful looking code for creating observable properties, so you can have a function fire when a property changes.



In my situation I need to do something when the object/property is created, not an existing property changed, and my limited understanding of such matters did not help me figure out if or how I could use that code to do this after much squinting.




The situation is: page loads a bunch of scripts. Some of the scripts create things that are needed by other scripts, e.g:



ThisStuff = (function () {
// blah blah
return self;
} ());


Some other code needs to initialize this ThisStuff, whenever it's available, which may be after the DOM is done loading. The user doesn't actually need ThisStuff right away, so it's fine for it to happen whenever the script is done loading. So I would like to do something along lines of:




$(document).ready(function() {
wheneverIsAvailable(window,'ThisStuff', function(object) {
object.init(args);
})
});


I realize there are other solutions to this problem (changing script order, or loading scripts on demand) but those are difficult because of the architecture. So I'm only interested in a way to do this versus other solutions. If jQuery offers some such functionality, that's fine also as I'm using it.


Answer




You could have a setInterval checking a number of times a second to watch the specific variable. You can check whether it is created using obj.hasOwnProperty(prop). When it is created, you invoke the function, and clear the interval.



It might be dirty but it might also just work fine for you.



Edit: I coded this for you: http://jsfiddle.net/jhXJ2/2/. It also supports passing additional arguments to the function.



window.__intervals = [];

function wheneverIsAvailable(obj, prop, func) {
var id = (Math.random()+"").substring(2);

var args = arguments;
window.__intervals[id] = window.setInterval(function() {
if(obj.hasOwnProperty(prop)) {
window.clearInterval(window.__intervals[id]);
func(Array.prototype.slice.call(args, 3));
// Call function with additional parameters passed
// after func (from index 3 and on)
}
}, 1000/ 50);
}


wheneverIsAvailable(window, 'test', function() {
alert(arguments[0]);
}, 'Woot!');

window.setTimeout('window.test = 123', 1000);

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...