xkj5ga
Last Updated: December 26, 2018
·
2.254K
· 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

5531

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

over 1 year ago ·
5540

@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 ·
5541

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

over 1 year ago ·
5544

@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 ·
5597

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 ·