简体   繁体   中英

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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