Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    WA
    WA is offline
    Administrator
    Join Date
    Mar 2002
    Posts
    2,596
    Thanks
    2
    Thanked 19 Times in 18 Posts

    Tips on creating self encapsulating scripts

    I thought we might use this thread to share some tips on creating self encapsulating scripts when coding, so to minimize the chances of conflicts occurring between our script and others on the same page. I'm sure Alex (mod of XML forum) will have something to say here heh.

    Tip on avoiding variable conflicts:

    One of the most common conflicts with scripts occurs with identical variable names. This is the result of coders picking common names as variables, such as x, y etc. One way to minimize this problem from occurring is to define variables as properties of a custom object:

    Code:
    var glidescript=new Object()
    glidescript.x=50
    glidescript.y=150
    glidescript.text="welcome to my homepage!"
    This way, we only have to worry about "glidescript" being unique on the page, and not any of its properties such as x, y, speed etc.

    Please add your tips here.
    - George
    - JavaScript Kit- JavaScript tutorials and 400+ scripts!
    - JavaScript Reference- JavaScript reference you can relate to.

  • #2
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    Once there is a significant amount of replies, you should make this thread sticky.

    Anyway, for DHTML effects I highly recommend looking into IE's element/ViewLink behaviors (not too complicated to learn at all), and Gecko's XBL (definitely a little tougher - but you have a resident expert frequenting these forums ).

    You can then assign elements their effect through CSS, instead of hardcoding references, which means infinite code reuse on the same page, and exactly 0 conflicts with other scripts (unless they also use a behavior/binding, which is when you'll need to look into the addBehavior() and addBinding() methods).

  • #3
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts
    WA,
    A good idea but what if you want 2 glidescripts on the same page?

    I find the best idea is to use the fact you can use OO methods in JavaScript
    PHP Code:
    function glider(textsxsy)
    {
        
    this.startX sx;
        
    this.startY sy;
        
    this.text text;
    }
    glider.prototype.glideTo = function(x,y)
    {
        
    this.endX x;
        
    this.endY y;
        
    alert("Start at " this.startX ":" this.startY);
        
    alert("Move to " this.endX ":" +  this.endY)

    and then you can create multiple gliders
    PHP Code:

        myGlider1 
    = new glider("Hello World", -100, -100);
        
    myGlider2 = new glider("Welcome", -1000);
        
    myGlider3 = new glider("Some More Text"0, -100);

        
    myGlider1.glideTo(100,100);
        
    myGlider2.glideTo(100,200);
        
    myGlider3.glideTo(100,300); 
    OO JavaScript is a little harder to learn but it is possible to turn a conventional procedural JavaScript into an Object so it won't interfere with other scripts or itself.

    It is just a pity that there seem to be very few public scripts that use OO methods to learn from.

    I have some links somewhere to how to create OO scripts. I'll post them when I find them.

    P.S.
    Here is an example Multiple xeyes.
    The answer does not come from thinking outside the box, it comes from realizing the truth :-
    "There Is No Box". [JavaScript Gadgets'n'Gizmos][JavaScript-FX]

  • #4
    WA
    WA is offline
    Administrator
    Join Date
    Mar 2002
    Posts
    2,596
    Thanks
    2
    Thanked 19 Times in 18 Posts
    Good tips guys. I think we also need to take into account rapid deployment though. For example, creating an object class is quite a bit more work than merely creating an object on the fly, and in many situations, the later alone will do nicely.

    How about another potential conflict that has to do with two scripts both accessing the same event handler? For example:

    Code:
    window.onload=dothis //first script
    window.onload=dothat //second script
    Any tips on invoking an event handler while leaving it open to other scripts? Not sure if it's even possible.
    - George
    - JavaScript Kit- JavaScript tutorials and 400+ scripts!
    - JavaScript Reference- JavaScript reference you can relate to.

  • #5
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts
    NOTE: I have put javascript code examples between [ php ] vbCode as it color codes the syntax (but it really is JavaScript).
    For example, creating an object class is quite a bit more work than merely creating an object on the fly, and in many situations, the later alone will do nicely.
    I agree. It should make converting existing scripts a lot easier.

    As for the "onload" one method you could use is
    PHP Code:
    //Save a reference to the existing onload handler
    var oldOnload window.onload;
    function 
    gliderStart()
    {
        
    //If there was an old onload handler, execute it
        
    if(oldOnloadoldOnload();

        
    //Code to initialize glider script
    }
    //point the window.onload to my handler
    window.onload=gliderStart
    This relies on your script being inserted last in the document. If another script simply assigns the onload handler :-
    window.onload=anotherFunc;
    then it will wipe out your handler.

  • #6
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts

    A better onload solution

    A better solution to the onload problem would be if the window object had an "addOnloadHandler()" method so you could add your init method to a chain of onload handlers without wiping out existing onload handlers. We can implement this ourselves with the following code.
    PHP Code:
    /**** Start onload Code ****/
    var initFuncs = new Array();
    function 
    addOnloadHandler(func)
    {
        
    initFuncsinitFuncs.length ] = func;
    }
    function 
    initAll()
    {
        for(var 
    i=i<initFuncs.length i++)
            
    initFuncs[i]();
    }
    window.onload=initAll;
    /**** End  - onload code ***/ 
    This code could be put into the head of all your documents
    You could also place it in an external ".js" file and include it into all documents that require an onload handler.
    You would then replace all
    "window.onload=myFunc"
    with
    "window.addOnloadHandler(myFunc);

    For example
    PHP Code:
    function myStart()
    {
        
    alert("My Start");
    }

    function 
    initMenus()
    {
        
    alert("Init Menus");
    }

    function 
    startGlider()
    {
        
    alert("Start Glider");
    }

    window.addOnloadHandler(myStart);
    window.addOnloadHandler(initMenus);
    window.addOnloadHandler(startGlider); 

  • #7
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Tip on avoiding function conflicts

    This is similar to the tip for variables but it allows you to include methods as well. Consider
    Script 1
    PHP Code:
    function moveTo(x,y)
    {
        
    glidescript.x;
        
    glidescript.y;

    Script 2
    PHP Code:
    function moveTo(x,y)
    {
        
    myDiv.style.x;
        
    myDiv.style.y;

    You could prepend each with some text, e.g...
    function glider_moveTo(x, y)
    but a better solution is to add the functions to your custom object
    PHP Code:
    glidescript.moveTo = function(xy)
    {
        
    glidescript.x;
        
    glidescript.y;
    }
    glidescript.moveTo(10,10); 

  • #8
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Tip on avoiding having to type the full variable name

    Tired of typing long variable names of your custom object. E.g...
    PHP Code:
    glidescript.glidescript.glidescript.speed;
    glidescript.glidescript.glidescript.speed;
    glidescript.moveTo(glidescript.xglidescript.y); 
    Then use the "with" keyword to get a shortcut
    PHP Code:
    with(glidescript)
    {
        
    speed;
        
    speed;
        
    moveTo(xy);

    (this is why it is better to add functions to your objects rather than just prepend some text)

  • #9
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Some good reading

    Here are some links. I will edit to add more when I find them
    Coding for portability
    ---------------------------
    http://www.13thparallel.org/?issue=2...ortability_one
    http://www.13thparallel.org/?issue=2...ortability_two

    OO Programing in JavaScript
    -----------------------------------
    http://www.webreference.com/js/column79/
    http://www.webreference.com/js/column80/
    Last edited by RoyW; 06-19-2002 at 04:35 PM.

  • #10
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    Don't want to destroy event handlers?

    Use the DOM2 Events standard addEventListener for Gecko, and IE's proprietary attachEvent:

    Code:
    function MyMouseMove(event) {
    // do stuff
    }
    
    if (typeof document.attachEvent != 'undefined')
      document.attachEvent('onmousemove', MyMouseMove);
    else if (typeof document.addEventListener != 'undefined')
      document.addEventListener('mousemove', MyMouseMove, false);
    Voila, you didn't remove anything that may have been assigned to document.onmousemove, but added an event to it nonetheless.

  • #11
    New Coder
    Join Date
    Jun 2002
    Posts
    47
    Thanks
    0
    Thanked 0 Times in 0 Posts
    It may sound arcane but be indulgent: my solution to this riddle was to make an object name so much shared as possible: write once, borrow everywhere.

    In Java, each class has its methods, at most you can have an interface (those strongly data typed languages really cause a significant waste of code with the strong call for overloaded methods: we have javas in a nutshell which exhibits for each class at times hundreds of functions that include the very same code and just a couple of commas different to accomodate different input data type). Each class incapsulates its methods.

    In my approach, each method is lent to each class, without implementing the interface.

    Basically was developed on layers for Dhtml:
    var foo= new layerManager("foo");

    now you have a method which is cognizant of how that constructor works
    function moveEllipse(){
    this...
    this...
    if(!this...){this...=...}
    }

    then you can borrow to each manager the method by using a second constructor:
    foo.moveEllipse=new managerMethod("moveEllipse")

    each layerManager can therefore hold methods with an identical name without this causing any conflict and with the method wrtitten only once and not thousand of times to accomodate differnent combinations of layers.

    foo.moveEllipse.execute() triggers the method on foo.

    I think it may be a curiosity to add to this thread for it is an attempt, partially successful, to solve the problem of shared names by pioneering exactly in the direction one wouldn't have ventured to. I called it ULMA (Universal Layer Management APPROACH), maybe it can give an interesting outlook for further developements on the thread issue.

    Just my two cents.
    Alberto http://www.unitedscripters.com/

  • #12
    Moderator
    Join Date
    May 2002
    Location
    Hayward, CA
    Posts
    1,460
    Thanks
    1
    Thanked 23 Times in 21 Posts
    RoyW beat me to it.
    "The first step to confirming there is a bug in someone else's work is confirming there are no bugs in your own."
    June 30, 2001
    author, Verbosio prototype XML Editor
    author, JavaScript Developer's Dictionary
    https://alexvincent.us/blog


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •