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...)Written by Pavel Pravosud
Related protips
5 Responses
Looks like you want to use => instead of -> here (coffeescript)
@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).
@koehr no, => preserve the current context, which is unimportant.
@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.
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. :)
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside