3

Assume I have the following simplified function.

var ex = document.getElementById('exampleElement'),
    data = {
        foo: 'Sample text'
    };

ex.addEventListener('click', function(evt, d) {
    evt.stopPropagation();
    this.innerHTML = d.foo;
}.bind(ex, null, data));

I realise binding ex to this is somewhat redundant in this particular case, but how can I bind the data parameter and still keep the event argument from being destroyed?

I can't seem to find the answer anywhere.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
stafffan
  • 482
  • 6
  • 17

1 Answers1

1

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

arg1, arg2, ...

Arguments to prepend to arguments provided to the bound function when invoking the target function.

Which means that your curried value will come before the event object. See this fiddle for an example:

http://jsfiddle.net/5w4vnvof/

var clickme = document.querySelector("#clickme");

clickme.addEventListener("click", function(value, event) {
    var newDiv = document.createElement("div");
    newDiv.innerHTML = value + "<br/>" + event.target.toString();

    document.body.appendChild(newDiv);
}.bind(clickme, "curriedValue"));
Community
  • 1
  • 1
Ray Wadkins
  • 876
  • 1
  • 7
  • 16