Keep track of property developments?

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

The answer to this question contains very useful code for creating observable properties, so you can have a start function when the property changes.

In my situation, I need to do something when an object / property is created, and not an existing property, and my limited understanding of such issues did not help me figure out if I can use this code for this after squinting a lot.

The situation is this: the page loads a bunch of scripts. Some of the scripts create things that other scripts need, for example:

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

Some other code should initialize this ThisStuffwhen it is available, which may be after loading the DOM. The user doesn’t really need it ThisStuffright away, so it’s normal when it will be executed whenever the script is loaded. So I would like to do something line by line:

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

I understand that there are other solutions to this problem (changing the order of the script or loading scripts on demand), but this is difficult due to the architecture. Therefore, I am only interested in a way to do this compared to other solutions. If jQuery offers some of these features, this is great too when I use it.

+5
source share
2 answers

setInterval . , obj.hasOwnProperty(prop). , .

, .

: : http://jsfiddle.net/jhXJ2/2/. .

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);
+2

, .

javascript- knockoutjs. , .

, , . , , , - ( , ), , .

, .

0

All Articles