简体   繁体   English

有人可以使用.bind()函数向我解释此代码吗?

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

I encountered this snippet (event handling) from the jQuery source code: 我从jQuery源代码中遇到了以下代码片段(事件处理):

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); this.bind(name,fn); work the same as element.addEventListener('event','callback()') ? element.addEventListener('event','callback()')吗?

I know the basics of javascript, but I do not know the more advanced parts of JavaScript. 我知道javascript的基础知识,但不了解JavaScript的更高级部分。 Since I taught myself, there are many holes in my JavaScript knowledge. 自从我自学以来,我的JavaScript知识有很多漏洞。 If anyone knows of a good source I could learn more advanced JavaScript from I would like to hear that too. 如果有人知道一个好的资源,我也可以从中学习更高级的JavaScript。

Thank you. 谢谢。

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(); 非常简单,我们将所有事件都放在一个数组中[click, focus ...]轻松地,我们在该数组上应用了foreach,然后代码的下一部分为jQuery原型$.fn.click()分配了一个函数,该函数将变成$('#me').click() ,最后是click(); function calls $.fn.bind(); 函数调用$.fn.bind(); which will call addEventListener() later, that's it. 稍后将调用addEventListener()

if you still wondering where is addEventListener() read about bind() in jQuery. 如果您仍然想知道addEventListener()在哪里了解 jQuery中的bind()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM