2

I'm creating a small canvas library in which I have an anonymous function which needs to reference to itself. However, I don't know how to do this. I have the following incomplete code:

var removeDragHandler = (function (object) {
  return function (e) {
    if (typeof object["dragend"] === "function") {
      object["dragend"](e);
    }
    removeEvent({
      element: window,
      event: "mousemove",
      callback: object["drag"]
    });
    removeEvent({
      element: window,
      event: "mouseup",
      callback: ????? //What here?
    });
  };
})(object);
addEvent({
  element: window,
  event: "mouseup",
  callback: removeDragHandler
});

Of course I could replace the ????? with arguments.callee, but then it doesn't work in strict mode. Are there any other options?

3
  • 1
    If your problem is just referencing the anonymous function, you should ask for that and not for "self deleting events". Commented Jun 4, 2012 at 17:53
  • @Bergi :P so true, I had to read it twice to get the actual useful info from there which is Of course I could replace the ????? with arguments.callee, but then it doesn't work in strict mode Commented Jun 4, 2012 at 17:56
  • @Bergi - You're right, I updated my post and deleted all irrelevant information. Commented Jun 4, 2012 at 18:00

1 Answer 1

2

You can give a name to the anonymous function. Note that there is a bug in older IE where the anonymous function leaks as a declared function in the outer scope but that should not be issue here since that outer scope is pretty empty anyway.

var removeDragHandler = (function (object) {
  return function once(e) {
    if (typeof object["dragend"] === "function") {
      object["dragend"](e);
    }
    removeEvent({
      element: window,
      event: "mousemove",
      callback: object["drag"]
    });
    removeEvent({
      element: window,
      event: "mouseup",
      callback: once
    });
  };
})(object);
Sign up to request clarification or add additional context in comments.

4 Comments

Of course, I can't believe I didn't think of that myself. I don't really worry about older IE versions, since this is a small library for the canvas element. Older IE versions don't support the canvas element and hence can't use this library at all. Thanks for your help!
I think you can avoid the IE leak by just storing the funcion in a variable instead of declaring it. Just do "var once; return once = function ..."
@Jbm true but then it's not NFE :(
Can I get a link to inner functions leaking to the outer scope in IE?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.