html - How to access a JavaScript object property with addEventListener? -
i'm displaying images dynamically added on click of html button. using addeventlistener want add on click function these images access property of object can displayed.
this code likes:
    var fruit = function(type, cost)         {             this.type = type;             this.cost = cost;             this.image = new image();             this.image.src = "fruits/" +type +".png";                            }     var fruitarray = new array();      fruitarray[0] = new fruit("apple", 0.35);     fruitarray[1] = new fruit("mango", 0.55);     fruitarray[2] = new fruit("orange", 0.15);      function printfruits()     {         var counter = 0;         var element = document.getelementbyid("div1");         for(counter = 0; counter < 3; counter++)         {             fruitarray[counter].image.addeventlistener("click", function fruittype() {                 window.alert(this.type);             });             element.appendchild(fruitarray[counter].image);          }     }   at moment i'm displaying 'fruitarray[counter].image.type' (which undefined). 
i want know if there way can derefernce image property in order display 'fruitarray[counter].type', appreciated!
you can use bind, like:
function printfruits() {     var counter = 0,         element = document.getelementbyid("div1"),         item;      function onclick() {         window.alert(this.type);     }      (counter = 0; counter < 3; counter++) {         item = fruitarray[counter];          item.image.addeventlistener("click", onclick.bind(item));         element.appendchild(item.image);      } }   the
bind()method creates new function that, when called, hasthiskeyword set provided value, given sequence of arguments preceding provided when new function called.
Comments
Post a Comment