Reputation: 5845
I've been dipping my toes into Javascript and now looking at the following piece of code:
var router = new(journey.Router)({
...
});
router.root.bind(function (res) { res.send("Welcome") });
Question: What is the root function above bound to? What does this binding do?
I understand that 'bind()' is supposed to bind the execution of a function to a specified object as a context. I do not understand how a function/method can be bound to an other function. All of the references I have looked at are talking about binding to an object.
Upvotes: 2
Views: 2100
Reputation: 17367
'root' is a getter method defined in journey.js (at line 145) as
get root() {
return this.get('/');
},
which is simply an expedient shorthand for
get('/')
And in this context, the call to bind will associate the provided callback function with the route defined as root, such that any requests that match the root path ('/') will be answered by the string 'Welcome'.
UPDATED
Upon further examination of the journey.js source, it appears the use of bind() in this context is not an example of currying at all.
Rather this particular bind() is defined as a function of the object returned by route() (which in turn is called by get()) in journey.js at line 131, and is simply used to set (or bind) the handler for a particular route.
IMPORTANT: This call to bind() IS NOT the same as Function.prototype.bind().
I'm leaving my previous answer below because I believe the information regarding currying still has value in this situation.
Upvotes: 4
Reputation: 1795
Not totally familiar with the object that you're using, but it's using javascript "anonymous functions" to create an object that contains a chunk of code so it can be passed around like a variable. It can later be called by appending the () onto the end.
See: http://helephant.com/2008/08/23/javascript-anonymous-functions/
Probably the most common use of this sort of thing is for setting a callback function, that is, when you call a function on router, when that function completes, it will finish by calling whatever you bound to it in the first place.
Say I'm using a generic javascript library (such as colorbox) to pop up a dialog on the screen and prompt the user for information. Once that gets done, or if the user closes the box without entering anything, I want the box to do something custom. I don't want to have to dig around in colorbox's source code to do this, so they allow places for all sort of callback functions. Say when the users enters the information and hits a button, it'll close the colorbox, submit ajax, and refresh the underlying page.
Upvotes: 0