javascript: assign function parameter if functioncall is a string? - javascript

Following example - the YoutubePlayer API
videoID.addEventListener('onStateChange', 'foo');
In the documentation they say, video.addEventListener(string: event, string: function).
That means the first parameter is the event (in my case onStateChange) and the second parameter is the function that is getting called when the even is triggered.
This youtube sample is just a good example, I've alredy had this question a few times before.
If the function to call is passed as a string, is there any chance to assign a a parameter to that function?
Imagine the function I want to call looks like this.
function foo(something) {
console.log(something).
}
It's obviously not possible to add a parameter to the function call is it? Likeā€¦
videoID.addEventListener('onStateChange', 'foo(videoID)');
Thank you for your information and answers.

You could do something like:
videoID.addEventListener('onStateChange', function()
{
foo(videoID);
});
...if I'm understanding you correctly.

Related

What do those numbers mean in the parenthesis after the function in javascript?

*Don't mind the jQuery syntax. It serves as an example only and not the focus of the question.
$('target').on('click',function(){
'do something'
},5);
What does the value of 5 do? Does it set an initial value? Can you have multiple values like:
},5,6,5);
or can you only have one value?
They are simply function parameters. There is nothing special about the 2nd parameter, which happens to be a function. For the sake of clarity you could also refactor the code to look like this:
$('target').on('click', doSomething, 5);
function doSomething(){
// do something
}
To see exactly what parameters you can pass to the .on() function I'd recommend reading the documentation.
This argument passes value to handler.
You can get value from event.data.
It must be single value.
If you want to pass multiple data, pass value by object.
$("button").on("click", 3, function(e) {
alert(e.data) // alert 3
});
Reference: http://api.jquery.com/on/

I don't want to run a function, just use it as a parameter, but it keeps popping

I have read in other answers that in order to use a function as a parameter, it needs to be written whatever;and not whatever()because this las option "calls" the function. But what if I need to specify a parameter of said function? I give an example:
I have this function to replace some content:
function navigate(content) {
var card = document.getElementById('informationdiv');
card.innerHTML = content;
}
And then I have another function that creates the content:
function productsheet(article) {
document.write(array_products[article].Name);
document.write(array_products[article].Number);
document.write(array_products[article].Type);
// and so on...
Then, I want to call the first function like this:
navigate(productsheet(article));
And instead of do the innerHTML replacement, it just runs productsheet(article)overriding everything else.
As I said, I found similar problems where the solution was to pass productsheetwithout (article), but in my case I need the article parameter, so productsheetknows what to print...
What is the suggested approach here?
Thank you very much!
If I've understood your question correctly, you need to pass an anonymous function to navigate and call your productsheet function within that:
navigate(function () {
productsheet(article);
});
However, I'm not really sure what you're trying to acheive... you probably want to get rid of those document.write calls and return a string from productsheet, and call the function instead of assigning a reference to it to innerHTML:
card.innerHTML = content();
There are much better ways to achieve what you want, but taking your code as starting point I would do as follows:
navigate(article);
function navigate(article) {
var card = document.getElementById('informationdiv');
card.innerHTML = productsheet(article);
}
function productsheet(article) {
//here you would return a string that has the format as how you would like to display it
return "... name, number, type ...";
}
Again, I think you should rethink the whole approach and throw this code away.

Passing an array in a single argument using jQuery deffered.resolveWith()

I have a jQuery deferred, which I an resolving like so:
deferredAction.resolve(returnArray);
and this is calling a callback like:
function someCallback(myArray) {
...
}
This works fine, the callback function receives the array. However I need to set the context of the callback function, so I used deferred.resolveWith like so:
deferredAction.resolveWith(someContext, returnArray);
The context is now being set correctly. However, it now seems as if the returnArray is being split up. My callback only receives the first item of the array.
Why is this happening, and how can I work around it?
The documentation states that you should pass the arguments in a single array. In your case:
deferredAction.resolveWith(someContext, [returnArray]);
I fixed this by putting square brackets around the return parameter:
deferredAction.resolveWith(someContext, [returnArray]);

Can someone explain why this is passing in an object

I have something like the following..
$(document).ready(function() {
$('#doReport').click(doReport);
});
function doReport(type) {
if (type === undefined) {
type = 'blah';
}
alert (type);
}
If I run doReport() from the console or standalone in the javascript with nothing in it, it will return 'blah' (as expected), and obviously if I call doReport('wibble'); it returns 'wibble' as you would expect.
But if I run it by clicking the element with ID doReport (utilising the bind I set up in .ready) it returns [object Object]
I don't understand why that would be the case.
The jQuery library passes your event handlers an "event" object. It will always be there. It's a "wrapped" or "fixed" version of the native browser object, making it somewhat easier to deal with.
Here is the documentation for such objects.
Also of note is the fact that jQuery will invoke your handler functions such that this refers to the DOM element for which the handler is being invoked.
Also also, as #Ericson578 points out in a good comment, jQuery allows additional parameters to be set up, which means that your handler may be passed additional parameters. That might be useful if you've got a single event handler function to be bound to different elements, but you'd like to qualify its behavior with some different flags or whatever based on the particulars of an element.
Event handlers receive an event object as a parameter.
This is because event handlers are triggered with an object (specifically, the event object) passed as the first argument.
This is the reason you see such syntax as
$('#doReport').click(function(e) {
If you want to call your function without any parameters, you'll need to create a wrapping function to do so:
$(document).ready(function() {
$('#doReport').click(function() {
doReport();
});
});
When jQuery calls the function passed as parameter to click, it passed event object as the argument hence you are getting the alert as [object Object].
Check this:
http://api.jquery.com/click/
From JQuery - .click()
.click( handler(eventObject) )
handler(eventObject)A function to execute each time the event is triggered.
Your doReport() function is getting an event object.
wrap it with another function if you need to pass an argument to your function.
$(document).ready(function() {
$('#doReport').click(function(event){
doReport('blah');
});
});

Accessing Parameters *and* Events in function from jQuery Event

This is a follow-up question to a different question I asked not too long ago. Typically, you can access an event in a function call from a jQuery event like this:
$item.live("click", functionToCall);
and in the function:
function functionToCall(ev) {
// do something with ev here, like check 'ev.target'
}
But what if I wanted to send a parameter to functionToCall() and access the event? So something like this, maybe? :
$item.live("click", functionToCall($(this)); // send over parameter this time
and
function functionToCall(ev, $clickedItem) {
// both accessible here?
alert(ev.type);
alert($clickedItem.attr('id'));
}
Would that be acceptable, or is there a different way to send a parameter? Because this way doesn't seem right to me. Any help would be appreciated. Thanks.
CLARIFICATION: I realize that an anonymous callback function would allow me to access both, but for various reasons too lengthy to get into in this post, I need to use a function call rather than the anonymous function. So my question deals strictly with the scenario when an external function needs to be called. Thanks.
UPDATE: My original question presented the scenario of needing to pass $(this) as a parameter to the external function. As it turns out, $(this) will be accessible in the function without even needing to pass it, because of the way jQuery reassigns values to "this" based on events. So performing this code should work for my original question:
$item.live("click", functionToCall);
and
function functionToCall(ev) {
alert(ev.type);
alert($(this).attr('id')); // display id of item that was clicked
}
However, as others have answered, there is a different scenario that involves needing to pass a different kind of variable over as a parameter, such as a simply string or int. In this case, as others have notes, it becomes more complicated. But there do seem to be sufficient answers here to satisfy this second scenario (namely, "currying"). Thanks.
You can curry or partially apply your function:
Something like this:
function functionToCall($clickedItem) {
return function (ev) {
// both accessible here
alert(ev.type);
alert($clickedItem.attr('id'));
}
}
Then you can use it like you want:
$item.live("click", functionToCall($(this));
Note: If you can't modify your original functionToCall because is "external", you can wrap it:
function wrapFunctionToCall($clickedItem) {
return function (ev) {
// call original function:
functionToCall(ev, $clickedItem);
}
}
// ...
$item.live("click", wrapFunctionToCall($(this));
.live('click', functionA(prm) {
return function(ev) {
// here you can use the prm and the event
}
}
I know the question's answered, but for what it's worth, here's a one-liner that works as well if you don't want to edit your original function(s):
$item.live("click", function() { functionToCall( $(this) ); });

Categories