Hello,

I just have a quick question about jQuery best practices...

I have been wondering for a while now, is it bad practice for me to
make references to objects outside of the block of code they are used
in?

For example, in my master JS file I might have this code:

===================

// Start closure:
$(function() {

        var $parentObj = $('#parentContianer');
        var $childObj1 = $('#childEle1');
        var $childObj2 = $('#childEle2');
        var $childObj3 = $('#childEle3');
        var $childObj4 = $('#childEle4');
        var $childObj5 = $('#childEle5');
        var $childObj6 = $('#childEle6');

        if($parentObj) { // Parent object exists, execute code block:
                ... do something with child objects ....
        }

});
// End closure.

===================

HTML:

===================

<body>

<div id="parentContianer">
        <div id="#childEle1"></div>
        <div id="#childEle2"></div>
        <div id="#childEle3"></div>
        <div id="#childEle4"></div>
        <div id="#childEle5"></div>
        <div id="#childEle6"></div>
</div>

</body>

===================

Should I avoid referencing those child objects only until the parent
object exists?

I really like keeping all of my used variables at the top of my JS (so
I know what vars I am using and such), but I am just not sure how to
best handle object references... I do not want to do unecessary
lookups.

Is there anyway I could do something like a simple PHP class, but with
JS (psuedo js/php code below):

===================

<?php

class Myclass {

        var $parentObj = $('#parentContianer');
        var $childObj1 = ''
        var $childObj2 = ''
        var $childObj3 = ''
        var $childObj4 = ''
        var $childObj5 = ''
        var $childObj6 = ''

        // Class constructor:
        function Myclass() {
                if($this->parentObj) {
                        $this->childObj1 = $('#childEle1');
                        $this->childObj2 = $('#childEle2');
                        $this->childObj3 = $('#childEle3');
                        $this->childObj4 = $('#childEle4');
                        $this->childObj5 = $('#childEle5');
                        $this->childObj6 = $('#childEle6');
                        Init(); // Call Init() method.
                } else { return false; } // If parentObj does not exist, quit.
        }
        function Init() {
                $foo1 = $this->childObj1;
                $foo2 = $this->childObj2;
                ... Do more stuff with the child objects here ...
        }

}

?>

===================

Basically, I want to keep my code organized and readable... But I also
want to keep the overhead minimal.


Hehe, am I making sense here?

Any tips/advice/links ya'll could send my way would be super
helpful!!!!

Thanks!
Cheers,
Micky Hulse

Reply via email to