[英]How do I convert several anonymous jquery functions into a single named function?
Is it possible to convert the following four anonymous jquery functions into one function that gets a parameter passed? 是否可以将以下四个匿名jquery函数转换为一个传递参数的函数?
this is what I have... 这就是我所拥有的......
dropZone.addEventListener("dragenter", this.dragEnter, false);
dropZone.addEventListener("dragover", this.dragOver, false);
dropZone.addEventListener("dragleave", this.dragLeave, false);
dropZone.addEventListener("drop", this.dragDrop, false);
... ...
this.dragOver = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragover";
}
this.dragLeave = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragleave";
}
this.dragEnter = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragenter";
}
this.dragDrop = function(ev) {
ev.stopPropagation();
ev.preventDefault();
this.className = "dragdrop";
}
I'm looking for something functionally similar to... 我正在寻找与...功能类似的东西
dropZone.addEventListener("dragenter", dropEvent(this,"dragenter"), false);
dropZone.addEventListener("dragover", dropEvent(this,"dragOver"), false);
dropZone.addEventListener("dragleave", dropEvent(this,"dragLeave"), false);
dropZone.addEventListener("drop", dropEvent(this,"dragDrop"), false);
... ...
function dragEvent(ev, label) {
ev.stopPropagation();
ev.preventDefault();
this.className = label;
}
You can do that using a partially-applied function: 您可以使用部分应用的功能执行此操作:
function dragEvent(that, label) {
return function(ev) {
ev.stopPropagation();
ev.preventDefault();
that.className = label;
}
}
You can read more about partial application in javascript here: http://benalman.com/news/2012/09/partial-application-in-javascript/ 您可以在此处阅读有关javascript中部分应用程序的更多信息: http : //benalman.com/news/2012/09/partial-application-in-javascript/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.