ghcjs / ghcjs-base

base library for GHCJS for JavaScript interaction and marshalling, used by higher level libraries like JSC
MIT License
45 stars 67 forks source link

Capture `this` in callbacks #61

Open iand675 opened 8 years ago

iand675 commented 8 years ago

The current callbacks into Haskell from JavaScript don't provide a means of accessing the this value of the current scope. It's an implicit argument to every function, yet the current callback code doesn't recognize this. I wrote some code to kind of brute-force bring this in as an argument for a Callback, so it's not impossible to work around, but first-class support in ghcjs-base would better reflect the reality of how JavaScript libraries often work.

For reference, here's a way to grab this:


function captureThis(f) {
  return function() {
    var args = Array.from(arguments);
    args.unshift(this);
    f.apply(this, args);
  };
}
-- we don't want to treat the wrapped version as a callback on the Haskell side
-- because there shouldn't be an attempt to release it.
foreign import javascript unsafe "captureThis($1)" captureThis :: Callback a -> JSVal