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?
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) {
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();