GibboK
GibboK

Reputation: 73938

Alternative to .bind

I receive error

typerror undefined is not a function

using the following code

var btnLeft = document.querySelector('' + this.config.el + ' .btn-carousel-sim-left');
btnLeft.addEventListener('click', this.snippet.carousel.previous.bind(this), false); // ERROR HERE

I suppose the .bind function is not available on the target browser.

I would like to know an alternative solution to bind (Notes: I can also use jquery 1.9.1).

Upvotes: 0

Views: 1250

Answers (2)

GibboK
GibboK

Reputation: 73938

I found a solution using the following script, credit JavaScript: The Definitive Guide, 6th Edition

Example 8-5. A Function.bind() method for ECMAScript 3

if (!Function.prototype.bind) {
    Function.prototype.bind = function(o /*, args */ ) { // Save the this and arguments values into variables so we can        // use them in the nested function below.       
        var self = this,
            boundArgs = arguments;
        // The return value of the bind() method is a function        
        return function() { // Build up an argument list, starting with any args passed          
            // to bind after the first one, and follow those with all args         
            // passed to this function.          
            var args = [],
                i;
            for (i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
            for (i = 0; i < arguments.length; i++) args.push(arguments[i]);
            // Now invoke self as a method of o, with those arguments           
            return self.apply(o, args);
        };
    };
}

Upvotes: 1

sifriday
sifriday

Reputation: 4472

I am a big fan of using bind, it makes my life a lot easier.

I use the polyfill at the bottom of this page to ensure bind works in all browsers:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Hope that helps - add a comment if you are unsure how to use a polyfill.

Upvotes: 2

Related Questions