Last Updated: December 26, 2018
·
2.745K
· rwz

JavaScript/CoffeeScript binding techniques for different environments

Suppose you want to do something similar to this:

# won't work, context is lost here
$.ajax({
  url: '/foo',
  success: myObj.myMethod
});

Client with jQuery:

success: $.proxy(myObj, 'myMethod')

Client with underscore:

success: _.bind(myObj.myMethod, myObj)

Node.js or client with newer browser:

success: myObj.myMethod.bind(myObj)

Vanilla JS, any browser:

success: function(){ return myObj.myMethod.apply(myObj, arguments); }

CoffeeScript:

success: -> myObj.myMethod(arguments...)

5 Responses
Add your response

Looks like you want to use => instead of -> here (coffeescript)

over 1 year ago ·

@matthewwithanm apply is the only was to pass all arguments directly to a function. If you know an easier way to do the same thing, please tell (there is none actually).

over 1 year ago ·

@koehr no, => preserve the current context, which is unimportant.

over 1 year ago ·

@matthewwithanm you're absolutely right, in this particular example a much simple code like that could work:

success: function(a1, a2, a3){ return myObj.myMethod(a1, a2, a3); }

but I wanted to make an example with kinda more unified and general way of doing binding where you're not concerned by the number of arguments.

over 1 year ago ·

I thought @koehr was correct that you should use => in the CoffeeScript example, because I assumed the $.ajax block was inside myObj. Great post, but this could be clearer. :)

over 1 year ago ·