0

I'm trying to pass arguments to a function, but can't figure out how to do this when method chaining .bind.

I suppose my question is two fold:

1) How do you pass the parameters to the callback function (in this case, printEvent) when you're using bind?

2) Furthermore, how do you actually pass the pointerdown event to the printEvent function?

var app = {  

  fruit : 'apple',

  printEvent: function(event){
    console.log(event + this.fruit );
  },

  eventListeners:function(){
    var target = document.getElementById('elementId');
    target.addEventListener('pointerdown', this.printEvent(event).bind(this));
  }

}
5
  • 1
    You mean target.addEventListener('pointerdown', this.printEvent.bind(this, 'pointerdown')); ? Commented Mar 17, 2017 at 1:26
  • Great, that answers the first question. :) Except, how do I actually pass in the pointerdown event itself. Right now, your solution only passes in a string Commented Mar 17, 2017 at 1:33
  • 1
    I thought you just wanted the string. In that case, just bind this. event will automatically be passed. Commented Mar 17, 2017 at 1:41
  • 1
    The relevant docs: developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Mar 17, 2017 at 1:43
  • As always, you don't call the function that you are passing as a callback? Commented Mar 17, 2017 at 1:57

1 Answer 1

1
var app = {
  fruit: 'apple',

  printEvent: function (event) {
    console.log(event.target, event.type, this.fruit)
  },

  eventListeners: function () {
    document.getElementById('elementId').addEventListener('pointerdown', this.printEvent.bind(this))
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.