What is passed with the bind in JS? - javascript

I am binding a select of a custom control to a function. I just want to clarify when I bind something like this
auditFileUpload.bind("select", uploadSelectfunction);
I know I can use the following function
uploadSelectfunction(e)
{
}
how is e getting passed? is it the events? or the object itself?
if I had a function like this, how would I bind it?
uploadSelectfunction(e, datatype)
{
}
auditFileUpload.bind("select", function() { uploadSelectfunction(events, "CSV" });
I tried events, it doesn't work..
sugesstions? clarifications?

The events parameter is simply the first parameter passed to the event handler/method. Just pass that on:
auditFileUpload.bind("select", function(events) { uploadSelectfunction(events, "CSV"
In the original version uploadSelectfunction is simply a pointer to a function that happens to take one argument. That events argument is defined inside the select event.
If you put an inline method instead (as you have done) you need to accept the events parameter, and pass it on to your code.

Related

How to pass arguments in a function reference

I'm looking for a way to save reference to two this objects in one function called after an event triggers in jQuery - this reference to the object the method is defined in (so I can use this.anotherObjectFunction()) and this reference to the object that triggered the event - so that I can use $(this).someJQueryFunction later on. The way I'd like to do it is by passing a this (function object) reference as an argument to the function. Unfortunately, the function is to be called by jQuery, not me, so it's passed as a reference, i.e.
someFunction: function()
{
...
cell.$el.on('click', 'li.multiselect-option', this.myClickFunction);
...
},
myClickFunction: function(objectReference)
{
//It should be able to call methods of that object.
objectReference.anotherFunction();
//And reference to the clicked item.
$(this).html("Don't click me anymore!!!");
}
I'm aware of the fact that I can do something like
cell.$el.on('click', 'li.multiselect-option', myFunction.bind(this));
...
myClickFunction: function(event)
{
this.anotherFunction();
$(event.currentTarget).html("Don't click me anymore!!!");
}
But this workaround doesn't really answer the question as it doesn't show how to pass additional arguments and in the future there may be a necessity to pass another (no, I don't want to register them as fields in the object).
No anonymous functions are allowed unless they can be easily removed with cell.$el.off() function that will remove them and only them (there are some other function associated with the same objects and events at the same time and they should remain intact).
UPDATE:
By no anonymous functions I mean solutions like:
var self = this;
cell.$el.on('click', 'li.multiselect-option', function() {
self.MyClickFunction(self, this);
});
They will not work because I'll have to use cell.$el.off() with the function reference (3-argument prototype) to remove this single function and only it, leaving other functions bound to both the same element and event.
Jquery .on event has option to pass the argument as parameter in event handler like this
cell.$el.on('click', 'li.multiselect-option', {arg1:'arg1' , arg2:'arg2'} , myFunction);
...
myClickFunction: function(event)
{
alert(event.data.arg1);
alert(event.data.arg2);
this.anotherFunction();
$(event.currentTarget).html("Don't click me anymore!!!");
}
Passing data to the handler
If a data argument is provided to .on() and is not null or undefined,
it is passed to the handler in the event.data property each time an
event is triggered. The data argument can be any type, but if a string
is used the selector must either be provided or explicitly passed as
null so that the data is not mistaken for a selector. Best practice is
to use a plain object so that multiple values can be passed as
properties.
or another way
cell.$el.on('click', 'li.multiselect-option', function() {
myClickFunction("hai" , "bye");
});
myClickFunction: function(arg1, arg2)
{
alert(arg1);
alert(arg2);
}
And I would also suggest a plugin-free solution to the question "how to supply a parameter to function reference"
Example
function x(a){
console.log(a);
}
setInterval('x(1)',1000);

JavaScript .click() unintentionally auto-starting

I created a custom variable/function that I am trying to execute when an element is clicked. For some reason, it decides to display onload and ignores the .click(). I've spent a while now trying to figure this out, but I'm not having much luck.
Here's my custom function:
var movebox = function (entry) {
$imagebox.css('left' , '0');
$('#wr').append(entry);
};
I'm attempting to call it like this, but it calls it when the page loads instead.
$l3.click(movebox('test'));
You're calling the movebox function immediately instead of passing the function as a reference to the click event handler. This is a common mistake in JavaScript. Instead, pass in your function inside of an anonymous function, like so:
$l3.click(function() {
movebox('test');
});
As an aside, the same mistake is oftentimes made with setTimeout, setInterval, addEventListener, and the infamous eval. Remember, when treating functions as arguments to another function, be sure to wrap them in anonymous functions.
You are calling the movebox then passing the returned value to click event handler, in this case you can use the .on() event registration helper to pass a data element to the event handler which can be accessed using the event object.
Try
var movebox = function (e) {
$imagebox.css('left' , '0');
$('#wr').append(e.data.entry);
};
$l3.on('click',{ entry: 'test'}, movebox);

onclick call with params

I've got a function, like this:
menu[0].onclick = function() {
filters.reset_all();
clients.get();
}
So it's called when user clicks on the first menu element. Now I need to call it form the other place and what I've done is this:
if (li.onclick) { //li and menu[0] above are the same
li.onclick.call();
}
and it works well.
But now I need to pass some params to onclick function. I've tried this .call(some_param); but arguments array in onclick is empty.
What am I doing wrong?
edit: changed into this:
menu[0].onclick = function(arg) {
console.log(arg);
filters.reset_all();
clients.get();
}
and
li.onclick.call(li,param);
still nothing
The first argument to .call() is the value for the this pointer. The 2nd, 3rd, etc... arguments get passed to the function. You only need to use .call() if you're explicitly trying to set the this pointer. Otherwise, you can just directly call the function li.onclick().
Event handlers are generally called by the system and when that happens, they are passed the event object as the first argument. If you want a function available that takes different arguments, you should create your own function for that and not use the event handling function. Your event handler can also call this other function if desired.
menu[0].onclick = function() {
myFunc("aaa");
}
function myFunc(arg1) {
// do whatever here
filters.reset_all();
clients.get();
}
if (li.onclick) {
myFunc("bbb");
}
it should be
call(object, param1, param2, param3...);
In your case you can write
li.onclick.call(li, param1);
The first parameter of call() is the context (in this case this) the rest of the parameters go into the arguments array in order. If you use apply() instead of call then you have just two parameters: apply(this, arguments_array)

Why wrapping into a function is required in .change() of jQuery?

Why this works in jQuery :
$('#selCars').change(function(){
alert( "I have changed!" );
})
but not this one :
$('#selCars').change(alert( "I have changed!" ) );
You pass a function reference to .change(). Your second example just has code there, not a function reference.
Your first example works because it passes a function reference which IS what is required.
A function reference is required because this is a callback that will be called at a later time. The .change() function which executes immediately needs to save the callback reference into it's own variable and then call it later when the change event actually occurs. To do that, it needs a function to call at that later time, not a raw piece of code.
And, the other answer is because, .change() was written to require a function reference. That's how the developers that spec'ed and wrote it designed it. If you want it to work, you have to follow their rules.
Because it's a callback, i.e. you're passing something that be called back later, so what you've to pass is a reference to a function, and that reference will be stored and called when the event will fire.
The change method doesn't store some code, it stores only a pointer to the function. Your function is called an event handler.
It's because .change() attaches an event handler to an element. The handler won't be called until the event has occurred.
Since in JavaScript, functions are just another datatype, you could also do this:
var handler = function(event) {
alert("I have changed!");
}
$('#selCars').change(handler);
Note that handler is a function, Whereas alert() would just return undefined.

Passing the event via an attached event listener

After spending so much time in jQuery, I'm rusty on my old fashioned JS...
The question: When attaching an event to an object that you want to trigger a function, how do you pass the event to said function?
Example function:
myFunction(e){
...
}
Example event attachment:
document.getElementById('blargh').onkeypress = function(){myfunction([what do I put here to pass the event?])};
Make the handler accept a parameter, say event, and pass it to your function:
document.getElementById('blargh').onkeypress = function(event){myfunction(event)};
The event handler always gets the current event passed as parameter... in the W3C model.
For IE you have to get the parameter via window.event. Thus, in the function you can write something like:
function(event) { event = event || window.event; myfuntion(event);}
you can try using arguments. This variable gets automatically populated in the local scope. It is an array of all the arguments that was passed into the function. If you pass arguments on to your myfunction, everything that was passed into the even handler will be passed as an array to myfunction.
document.getElementById('blargh').onkeypress = function(){myfunction(arguments)};
function myfunction(args)
{
alert(args[0]);
}

Categories

Resources