.proxy (cached) vs .bind

by plantface

HTML

<p>(<a href="http://stackoverflow.com/questions/18848343/underscore-bind-vs-jquery-proxy-vs-native-bind#answer-22860661">context</a>)</p>
<p>Assign both event handlers with the 'on' button and then remove them using the ''off' button. You will see that only the $.proxy versions is actually removed as jQuery returned the same reference when proxying the method to the same Object</p>
<div>
    <button id="proxyFire">fire click event</button>
    <button id="proxyOn">on</button>
    <button id="proxyOff">off</button> <span id="outputProxy"></span>
</div>
<div>
    <button id="bindFire">bind click event</button>
    <button id="bindOn">on</button>
    <button id="bindOff">off</button> <span id="outputBind"></span>
</div>

JavaScript

var obj = {
    proxied: function () {
        $('#outputProxy').text('proxied event handler executed');
    },
    bound: function () {
        $('#outputBind').text('bound event handler executed');
    }
}

// proxy / bind remove clickhandler
$('body').on('click', '#proxyOn', function () {
    $('#outputProxy').text('');
    $('body').on('click', '#proxyFire', $.proxy(obj, 'proxied')); // adds event handler
});
$('body').on('click', '#bindOn', function () {
    $('#outputBind').text('');
    $('body').on('click', '#bindFire', obj.bound.bind(obj, 'bound')); // adds event handler
});

// proxy / bind add clickhandler
$('body').on('click', '#proxyOff', function () {
    $('#outputProxy').text('');
    $('body').off('click', '#proxyFire', $.proxy(obj, 'proxied')); // does not remove event handler as 2nd call of doStuff.bind(thing) always returns a new/different function
});
$('body').on('click', '#bindOff', function () {
    $('#outputBind').text('');
    $('body').off('click', '#bindFire', obj.bound.bind(obj, 'bound')); // DOES remove handler, as a second call to $.proxy(doStuff, thing) is smart enough to know about similar use-cases
});