Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain this code using the .bind() function to me?

I encountered this snippet (event handling) from the jQuery source code:

var events = ['click', 'focus', 'blur', …];
jQuery.each(event,function(i,name){
    jQuery.prototype[name] = function(fn){
        return this.bind(name,fn);
    };
});

Can someone explain this to me? How does the this.bind(name,fn); work the same as element.addEventListener('event','callback()')?

I know the basics of JavaScript, but I do not know the more advanced parts of JavaScript. Since I taught myself, there are many holes in my JavaScript knowledge. If anyone knows of a good source I could learn more advanced JavaScript from I would like to hear that too.

like image 825
Progo Avatar asked Oct 01 '22 23:10

Progo


People also ask

What is the function of bind ()?

bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

What is bind () in JS?

JavaScript Function bind() With the bind() method, an object can borrow a method from another object. The example below creates 2 objects (person and member).

What is use of call () apply () bind () methods?

Call invokes the function and allows you to pass in arguments one by one. Apply invokes the function and allows you to pass in arguments as an array. Bind returns a new function, allowing you to pass in a this array and any number of arguments.

Do you think you can pass multiple arguments inside the bind () and call () methods?

You can bind multiple arguments multiple times, exactly as partial application, but the context object only once, you can't override it once you bound it, because this is defined by specs that I linked: "The bind() function creates a new function (a bound function) with the same function body (internal call property in ...


1 Answers

it's quite simple we have all events in an array [click, focus ...] easily we apply a foreach on that array and next part of code assign a function to jQuery prototype $.fn.click() which will become $('#me').click(), and finally this click(); function calls $.fn.bind(); which will call addEventListener() later, that's it.

if you still wondering where is addEventListener() read about bind() in jQuery.

like image 129
PRAISER Avatar answered Oct 05 '22 13:10

PRAISER