zhuanzhou
zhuanzhou

Reputation: 2453

what's the line meaning in javascript

function bind( obj, type, fn ) {
    if ( obj.attachEvent ) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
        obj.attachEvent( 'on'+type, obj[type+fn] );
    } else
        obj.addEventListener( type, fn, false );
}

i am new to javascript, the above code is from the internet. i don't understand the above function well, expect someone can explain it to me. thank you, why it declare three argument(obj, type, fn). obj['e'+type+fn] what's this line meaning.

Upvotes: 1

Views: 422

Answers (4)

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

It's used to attach events to objects dynamically.

For example to assign click event to some element:

var oDiv = document.getElementById("myDiv");
bind(oDiv, "click", MyClickHandler);

This will bind the click event of element with ID myDiv and execute function called MyClickHandler when that element is clicked.

Working example: http://jsfiddle.net/sDwvP/

These days such things are considered "old school" or obsolete, you better use full scale library like jQuery.

Upvotes: 1

Jon
Jon

Reputation: 437754

This function accepts three parameters:

  1. An object (specifically, a DOM node) that it will set an event handler on
  2. The event which will have the handler attached to it (e.g. "click")
  3. A function which is the event handler

It then creates two "helper" functions and uses them to assign the event handler:

obj['e'+type+fn] = fn; // helper #1
obj[type+fn] = function(){obj['e'+type+fn]( window.event );} // helper #2
obj.attachEvent( 'on'+type, obj[type+fn] ); // assigns event handler

The lines with the obj[something] syntax are simply accessing (getting/setting) a member of obj whose name is variable. For example, this:

var name = "alert";
window[name]();

does the same thing as this:

window.alert();

However, in the first case you have the value of name coming from a variable instead of being hardcoded.

Upvotes: 1

Tomas Aschan
Tomas Aschan

Reputation: 60674

In JavaScript, there is an equivalence between objects and hash sets. Thus, saying obj['abc']=123; is equivalent to obj.abc=123. By using the hash set notation, you can build your property names dynamically - in this case by concatenating 'e' with the values of type and fn.

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318698

obj['e'+type+fn] accesses the attribute of obj with the name 'e' + type + fn.

With type='abc' and fn='foo', it would access obj.eabcfoo.

Upvotes: 2

Related Questions