开发者

Write JavaScript Event to Pass to Inherited JavaScript Class

I have a Javascript class aaa that asynchronously loads data from our embedded Linux board via CGI.

I have a inherited class aaa.bbb that has functions that need to request server data from aaa

I currently initiliase both class via

document.addEventListener('DOMContentLoaded', aaa.methods.init, false);
document.addEventListener('DOMContentLoaded', bbb.methods.init, false);

What I really want is this:

document.addEventListener('DOMContentLoaded', aaa.methods.init, false);
document.addEventListener('aaa.onServerDataLoaded', bbb.methods.init, false);

However, is it possible to write a function in my aaa library that when the first server data is asynchronously loaded the other library are initialised开发者_开发百科?

How would aaa.onServerDataLoaded look?

// The XHR callback
function serverDataCallback(event) {
    if ((event.target.readyState === 4) && (event.target.status === 200)) {
        onServerDataLoad();
    }
};

// The event to bubble up
function onServerDataLoad() {
    // Erm...?! :)
};


You can have aaa dispatch a custom event.

function serverDataCallback(event) {
  if ((event.target.readyState === 4) && (event.target.status === 200)) {
    var evt = document.createEvent("Event"); 
    evt.initEvent("onServerDataLoaded", true, true); 
    document.dispatchEvent(evt); 

  }
};

Then you can actually bind one or more event-listeners to this event.

document.addEventListener('onServerDataLoaded', function(){
  bbb.init(); 
}, false);

Please be aware that this functionality might not be available in all browsers. Most Javascript-Libraries provide similar functionality in some x-browser way.

Have a look at MDN for more in-depth info:

https://developer.mozilla.org/Creating_and_triggering_custom_events


If you are using a javascript library why do you want to check for readyState and status ? From whatever i understood from your query, you have two Libraries i hope they are Ajax libraries say YUI(aaa.aaa) and jquery(aaa.bbb) so you can call the jquery initialization methods on response handler of YUI AJAX request

YAHOO.util.Event.onDOMContentReady(function(){
//Code to initialize your YUI library (aaa.aaa)
});

YAHOO.util.Connect.asyncRequest("POST", req, {
"success" : function(){

//Call you jquery (aaa.bbb)initialization functions here

}
});

I hope this helps you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜