开发者

OOP JavaScript - can't assign onclick event handler on page load

开发者 https://www.devze.com 2023-02-04 15:25 出处:网络
I\'m trying to do a custom tabs system using JavaScript. However, in order to reuse the code I want to write it in OOP style. This what I have so far:

I'm trying to do a custom tabs system using JavaScript. However, in order to reuse the code I want to write it in OOP style. This what I have so far:

function Tabs()
{

    this.tabArray = new Array(arguments.length);
    this.tabArrayC = new Array(arguments.length);
    
    for(i=0;i<arguments.length;i++)
    {
        this.tabArray[i] = arguments[i];
        this.tabArrayC[i] = arguments[i]+'_content';
    }
    
    this.setClickable = setClickable;

    function setClickable()
    {   

        for(i=0;i<this.tabArray.length;i++)
        {
                        
                document.getElementById(this.tabArray[i]).onclick = function()
                {
                    
                    alert(this.tabArray[i]);
                                    
                }
            
        }
                
    }
    
}

function init()
{
    tab = new Tabs('tab1','tab2','tab3','tab4');
    tab.setClickable();
}

window.onload = init();

Now here's the deal. I want to assign the onclick event handler to every tab that has been passed in Tabs 'class' constructor. So later in the code when I write something like:

<div id="tab1">Tab1</div>
<div id="tab2">Tab2</div>
<div id="tab3">Tab3</div>
<div id="tab4">Tab4开发者_运维百科</div>

The code which has been set up earlier:

document.getElementById(this.tabArray[i]).onclick = function()
{
                    
                    alert(this.tabArray[i]);
                                    
}

... would be executed. I hope I explained that well enough. Any ideas?


There are three issues with your setClickable function (edit: and an issue with how you're calling init):

  1. this will have a different meaning within the event handler you're generating than you expect. (More here: You must remember this)

  2. A closure (a function that closes over data like your i variable) has an enduring reference to the variable, not a copy of its value. So all of the handlers will see i as of when they run, not as of when they're created. (More here: Closures are not complicated)

  3. You're not declaring i, and so you're falling prey to the Horror of Implicit Globals.

Here's one way you can address those:

function setClickable()
{   
    var i;           // <== Declare `i`
    var self = this; // <== Create a local variable for the `this` value

    for(i=0;i<this.tabArray.length;i++)
    {
                                                         // v=== Use a function to construct the handler
        document.getElementById(this.tabArray[i]).onclick = createHandler(i);
    }

    function createHandler(index)
    {
        // This uses `self` from the outer function, which is the
        // value `this` had, and `index` from the call to this
        // function. The handler we're returning will always use
        // the `index` that was passed into `createHandler` on the
        // call that created the handler, so it's not going to change.
        return function() {
            alert(self.tabArray[index]);
        };
    }
}

...and as goreSplatter and Felix point out, this line:

window.onload = init();

...calls the init function and uses its return value to assign to onload. You mean:

window.onload = init;

...which just assigns init to the onload event.


Off-topic: You might consider using the newer "DOM2" mechanisms for attaching event handlers instead of the old "DOM0" way of using the onXYZ properties and attributes. The new way is called addEventListener, although sadly Internet Explorer has only recently added that (but it has attachEvent which is very similar). If you use a library like jQuery, Prototype, YUI, Closure, or any of several others, they'll smooth out those differences for you (and provide lots of other helpful stuff).


Problematic:

function init()
{
    tab = new Tabs('tab1','tab2','tab3','tab4');
    tab.setClickable();
}

window.onload = init();

In this case, window.onload will be undefined, since init() returns nothing. Surely you meant

window.onload = init;

?

0

精彩评论

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