Binding Arguments with Bind

By  on  

One of my favorite and most essential Function method is bind, a function we added to MooTools when it wasn't featured in the JavaScript language itself. We often think of using bind to simply bind a method's call to its host object, but did you know you can also bind arguments with the host object?

You've probably done something like this:

this._onTargetAvailable = this._onTargetAvailable.bind(this);

That pattern is frequently used, especially in classed-based code or when passing callback functions. What you may not often see is bound arguments:

this._onTargetAvailable = this._onTargetAvailable.bind(
    this,
    arg1,
    arg2,
    arg3
);

Binding arguments gives you more power in how your bound function is used! Whenever onTargetAvailable is called, the arguments you provide will be in that order, and any additional arguments will be added to the end of the argument list!

Recent Features

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

Incredible Demos

  • By
    Drag & Drop Elements to the Trash with MooTools 1.2

    Everyone loves dragging garbage files from their desktop into their trash can. There's a certain amount of irony in doing something on your computer that you also do in real life. It's also a quick way to get rid of things. That's...

  • By
    MooTools onLoad SmoothScrolling

    SmoothScroll is a fantastic MooTools plugin but smooth scrolling only occurs when the anchor is on the same page. Making SmoothScroll work across pages is as easy as a few extra line of MooTools and a querystring variable. The MooTools / PHP Of course, this is a...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!