1

I have an object literal pattern used in a code and I'm trying to pass the object name as reference to another function using 'bind'. I also need to pass a second parameter but when I do this I lose access to 'event' object.

var obj = {
  init: function() {
    this.trig();
  },

  trig: function() {
    $('.addButton').on('click', this.doSomething.bind(this, secondParameter))
  },

  doSomething: function(e,args) {
    e.preventDefault(); // erroring here e.preventDefault is not a function 

    //rest of the code 
  }
}

obj.init();

Any idea how I can send a second parameter whilst still having access to event object?

ConsoleLog
  • 501
  • 3
  • 12
  • 1
    `doSomething: function(e)` -> `doSomething: function(arg, e)` or `this.doSomething.bind(this, secondParameter)` -> `function(e) { return this.doSomething(e, secondParameter) }` – VLAZ Mar 29 '22 at 09:55
  • Thanks @VLAZ - that seems to work. For clarity, so 'event' object is now passed as the second parameter rather than first? – ConsoleLog Mar 29 '22 at 10:03
  • 1
    It's passed last after all bound parameters – pilchard Mar 29 '22 at 10:04

2 Answers2

2

doSomething only accepts one parameter. If you want it to accept two then you need to write it that way.

See the MDN documentation for bind:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

So you need to put variables to accept the bound arguments before the variable to accept the event object argument:

doSomething: function (boundArgument, e) {
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks @Quentin. Sorry, I've written it that way with two parameters in my actual code, I completely forgot to include in the code snippet. – ConsoleLog Mar 29 '22 at 10:05
  • @ConsoleLog — Your edit to the question shows you haven't. You put the variables for the bound argument after `e` instead of **before** it like I said in this answer. – Quentin Mar 29 '22 at 10:07
  • yeah, that's where I mixed up the order of parameters, hence the error. The code snippet is showing how I've written it in my actual code, which was throwing the error. Thanks again – ConsoleLog Mar 29 '22 at 10:09
-2

there is no need of using bind since doSomething is already a methode of the object so you just have to pass the event as argument

var obj = {
  init: function() {
    this.trig();
  }

  trig: function() {
    $('.addButton').on('click', (event) => this.doSomething(event))
  },

  doSomething: function(e) {
    e.preventDefault(); // erroring here e.preventDefault is not a function 

    //rest of the code 
  }
}

obj.init();
Thibaud
  • 1,059
  • 4
  • 14
  • 27