Guesser
Guesser

Reputation: 1857

bind not saving value as expected

var trackDay = new Date(2013, 10, 1);


alert(trackDay);

img.addEventListener("click", function(trackDay){                            
    alert(trackDay);
}.bind(null,trackDay),true); 

trackDay.setDate(trackDay.getDate()+1);

This alert on the click event produces the value for the incremented date when I want it to be the first value.

Upvotes: 1

Views: 53

Answers (2)

katranci
katranci

Reputation: 2571

Assuming that you cannot / don't want to use a second variable than you can pass the string representation of the date object with bind and create a new date object out of that string inside your callback function.

Check the plunker here

var trackDay = new Date(2013, 10, 1);

alert(trackDay);

img.addEventListener("click", function(trackDay){
    var date = new Date(trackDay);
    alert(date);
}.bind(null,trackDay.toString()),true); 

trackDay.setDate(trackDay.getDate()+1);

Upvotes: 1

jameslafferty
jameslafferty

Reputation: 2182

Does the jsfiddle do what you want?

Html:

<img src="http://placekitten.com/100/100" />

JavaScript:

(function () {
    'use strict';
    var img;
    function trackDay (val) {
        return function () {
            alert(val);
            val += 1;
        }
    }
    img = document.getElementsByTagName('img')[0];
    img.addEventListener("click", trackDay(0), true);
}());

Upvotes: 0

Related Questions