开发者

How to acces a global JS-Object in another .js-File

How do i acces an object which was initialized in my HTML-Document?

My HTML-Document looks like this:

    ...

<script type="text/javascript" id="controller">var controller = false;</script>

    ...

<body onload="controller = new CTRLclass()">

    ....

How do I call controller.doAMethod() in an external Javascript-File using DOM-Operations or simmilar?

edit: PPL, i have开发者_StackOverflow社区 many .js-Files and my controller is creating an instance of another class in his constructor. In the created instance of the class i need acces to the controller to call an update-Function. Like: controller -> creates instance of class. class -> needs to call controller.update(). How do i acces controller in 'class' - Thats all

THX!


You don't need the onload tag to initiate onload tasks. Just put this is the external javascript file:

var controller = false;
function Init(){
    controller = new CTLRclass;
}
function addEvent(el, eType, fn, uC) {
    var uC = uC || true;
    if (el.addEventListener) {
        el.addEventListener(eType, fn, uC);
        return true;
    } else if (el.attachEvent) {
        return el.attachEvent('on' + eType, fn);
    } else {
        el['on' + eType] = fn;
    }
}
addEvent(window, 'load', Init);


I actually can't envisage why you would want to do the above. Simply strip out all of the Javascript in the above, so all you have is:

...

<script type="text/javascript" src="myjsfile.js"></script>

...

<body>

....

And in myjsfile.js do somthing like

window.onload = function(){
    var controller = new CTRLclass();
}

If it must be global, then you can move it outside of the onload function:

var controller = false
window.onload = function(){
    controller = new CTRLclass();
}

Use of jQuery would make it more elegant, of course, as you wouldn't risk overriding any existing onloads:

var controller = false
$(document).ready(function(){
    controller = new CTRLclass();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜