如何将多个匿名jquery函数转换为单个命名函数?

时间:2012-10-04 18:15:50

标签: javascript jquery

是否可以将以下四个匿名jquery函数转换为一个传递参数的函数?

这就是我的......

    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";
}

我正在寻找与...功能类似的东西。

    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;
}

1 个答案:

答案 0 :(得分:2)

您可以使用部分应用的功能来执行此操作:

function dragEvent(that, label) {
  return function(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    that.className = label;
  }
}

您可以在此处阅读有关javascript中部分应用的更多信息:http://benalman.com/news/2012/09/partial-application-in-javascript/