0

I'm having trouble wrapping my head around the proper use of bind and the reference to past links being opened in my on click handler.

This function receives an array of 4 links. I simply want to open the correct link on click.

Links 2 and 3 work because they are bound to the window object. Links 0 and 1 will work on the first array that is passed but when a new array of links is passed to the function, when clicked, it will open the previous link and not the one that was most recently passed to the function.

I know that adding values to the window object is bad practice so I've been trying to figure out a better way to implement it while gaining a better grasp on bind,apply, and call. (If even necessary here).

Why is it that the first 4 links passed are correct but any other time links are passed, it will continue to reference and open the initial set of links?

links = function(linksArr) {
    var that = this;
    this.linkArray = linksArr;
    //Create an object from array in attempt to get correct link on event click
    var linkReference = linksArr.reduce(function(all,item,index){
       all[index] = item;
       console.log(all);
       return all;
    },{});
   //Does not work. Attempted use of bind
    $('.link0').on("click", function () {
        window.open(linkReference[0], '_blank');
    }.bind(linkReference));
    //Does not work. Trying to apply the proper links through the apply method
    $('.link1').on("click", function () {
        window.open(linksArr[1], '_blank');
    }.apply(null,linksArr));
    //Works
    $('.link2').on("click", function () {
        window.open(that.linkArray[2], '_blank');
    });
    //Works
    $('.link3').on("click", function () {
        window.open(that.linkArray[3], '_blank');
    });
};`
  • You don't need `bind`, `apply` or `call` here. Your code doesn't seem to be object oriented (your use of `this.linkArray` seems unnecessary, but we'd need to see the rest of the code, I suppose). If you want to know how they are used - check elsewhere: https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind – Adam Jenkins Aug 02 '17 at 19:19

1 Answers1

1

bind() makes the element you bind with be the 'this' inside the method. You should use 'this' as the reference, not the name you used when you bound.

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

Taplar
  • 24,788
  • 4
  • 22
  • 35