My call on function wont work? [duplicate] - javascript

I have a jQuery onClick handler, writed with an anonymous function like that:
$("#selector").on("click" function(){
// do something
})
I would generalize the anonymous function extracting the logic in a named function, that drive me to something like:
$("#selector").on("click" namedFunction())
function namedFunction(){
// do something
}
To me seemed a good solution. But there's a drawback since the namedFunction is executed as soon script is loaded. Here you can test the bad behaviour.

Just pass the reference of that function itself.
Try,
$("#selector").on("click", namedFunction);

You don't need the () for your function here:
$("#selector").on("click", namedFunction)

Or a shorter version
$("#selector").click(namedFunction);

To pass custom parameters to namedFunction use:
$("#selector").on("click", null, {param1: param1}, namedFunction);
namedFunction(event) { console.log(event.data.param1); }

try like
function namedFunction(){
alert("Hello world!")
}
$("#clickTester").on('click', namedFunction)
Updated Fiddle

Named function[view jsFiddle]
Function namedFunction () {
alert("Hello world!");
}
$("#clickTester").on('click', namedFunction);
Anonymous function [view jsFiddle]
$("#clickTester").click(function(){
alert("Hello world!");
});

Related

Meteor how to call another function in current function?

I have a function in helpers. I want to call that function in my next function. How can I fall it ?
'first_func' ()
{
return "hello";
},
'second_func' ()
{
return this.first_func();
}
This is not working. I want to call first function in second one.
Thank YoU!
With the way you're trying to do this, you would not need this. So you would be able to call the first function like so:
function first_func() {
//`this` is bound to first_func()
return "hello";
}
function second_func () {
//`this` is bound to second_func()
return first_func();
}
second_func(); // returns 'hello'
It appears, however, that you're trying to call functions within a class or a method. I can't guess at how or why, though, so please see the answer at Can you write nested functions in JavaScript?
Like #thatgibbyguy says, you can just define a function in the same file and use it. In a Meteor template helper, this is the data context of the helper, not the template instance itself.
Template.myTemplate.helpers(
first_func(){
return myFunction();
},
second_func(){
return myFunction();
}
);
function myFunction(){
return "Hello"
}
You can also register a global helper which can be used from any template

Not able to define function

I am writing something like
(function($){
function showAlert(){
alert('test');
}
})(jQuery);
and when I tried to run showAlert(), it's saying showAlert() is not defined.
Can anyone suggest why ?
The scope of a variable in javascript is either
the global scope
the function in which it is defined
showAlert is a variable. It's only available in the scope of the external function you wrote.
If you want to define a function for the external scope, define it in the external scope.
I suppose you're calling that function outside IEFE function.
Calling it outside won't work as it is not in global scope. The IEFE is creating a closure of which , showAlert becomes a part and not of global scope which is window
Do this:
(function($){
window.showAlert = function(){
alert('test');
}
})(jQuery);
It doesn't make sense to put a function declaration inside IEFE unless otherwise it is a jquery plugin. So, just remove it:
function showAlert(){
alert('test');
}
You're Creating A function inside a self executing anonymus function ie. $(document).ready() or $(function()....
So your function is in local scope of that function. Simply Means You cant access that in outside of that function.
So to make it accessible just make it global.
In JavaScript window is global object. So to make your function global, use that object as follows:
$(document).ready(function() {
function showAlert()() {
alert('test');
}
window.showAlert=showAlert(); //NOTE THIS, IT IS IMPORTANT.
});
Now you can access it elsewhere in your JS.
Here is working Fiddle
Hope it'll help you! cheers :)..
If you want to extend jQuery with your function just add function to jQuery object.
Like this:
(function ($) {
$.extend({
showAlert: function () {
alert('test');
}
});
}(jQuery));
Separate this code into file with name jquery.showAlert.js, include it after jquery library
and after this you can use function in this way:
$.showAlert()
Best regards.
This should work!
function showAlert(x) {
alert(x);
}
showAlert($('#anyElementId').val());
Assign the variable X for function and your alert. Then pass your element val into your function call.
Demo: http://jsfiddle.net/94ZtT/

Using defined function instead of anonymous function as callback

Why isn't it possible to use a defined function as event callback?
<div id="me">
<input>
</div>
$(document).ready(function(){
// $("#me").on('keyup', 'input', doit()); # doesn't work
// $("#me").on('keyup', 'input', 'doit'); # neither does this
$("#me").on('keyup', 'input', function() {
doit();
}); // well, this one works of course
});
function doit() {
console.log($("input").val());
}
You need to pass the function in as a parameter.
$("#me").on('keyup', 'input', doit);
You should pass the function, not call it
$("#me").on('keyup', 'input', doit)
To clear why that is wrong, see this example:
$("#me").on('keyup', 'input', (function() {
doit();
})());
Here you are passing an anonymous function and invoking it immediately, which is not what the event handler expects.
The problem is not in the difference between anonymous or not, the problem is that you are invoking the function instead of passing it.
When you pass in doit() (with the "()") as the callback, you're actually running the function at that point and passing in the return value of the function (likely undefined) as the callback. If you pass in just a reference to the named function doit then the function will be executed as the callback.
when you say something=function(){ blah } in js, it stores that as text and parses it on the fly - so yes, you can.
For example:
CallMe = function(){ alert("blah!"); }
bobsCallback.setFunction( CallMe );
CallMe is like any other variable, but it's contents is the js for the function.
You can pass it around as a callback, or invoke like so:
alert("calling CallMe...");
CallMe();

Pass a function as parameter in jQuery?

I would like to pass to a jQuery function a regular function, instead of the usual anonymous function, but I'm not sure how such a thing could be done.
Instead of this:
function setVersion(feature) {
$.post("some.php", { abc:"abc" },
function(data){
// do something here
}, "json");
}
I would like to do this:
function foo(data){
// do something here
}
function setVersion(feature) {
$.post("some.php", { abc:"abc" }, foo, "json");
}
Thank you.
Yeah, already works. But you want it probably look like this:
function setVersion(feature, myFunction) {
$.post("some.php", { abc:"abc" }, myFunction, "json");
}
setVersion(blah, foo);
Should run just fine.
I believe jQuery is actually meant to use the regular function, called by name. Using the anonymous function is simply a replacement for a named function that would otherwise be passed.
Yes, that is exactly how you do it.

Inline functions and other method's scope

How do I make the myFunction visibile for the in-line function in .ready() event?
$(document).ready(function() {
...stuffs...
myFunction(par1, par2, anotherFucntion_callback);
}
);
function anotherFunction_callback(data) {
..stuffs..
}
I didn't quite catch your question. Do you mean that you want to pass "myFunction_callback(data)" as the last argument in your:
myFunction(par1, par2, anotherFunction_callback);
, including that "data" parameter?
In that case the solution is pretty standard, write this before that one:
var temp = function() { anotherFunction_callback(data) };
an alternative syntax is:
function temp() { myFunction_callback(data) };
// even though this looks just like a free function,
// you still define it inside the ready(function())
// that's why I call it "alternative". They are equivalent.
In general, if you want to pass a function with 1 or more arguments to another function, you use that format. Here, we basically create a new no-argument function that calls another. The new function has access to the "data" variable. It's called "closure", you may want to read more on that.
Of course, if the callback require no argument, you can just use the original function name.
I hope this helps.
ps: You can even inline the function declaration, making it anonymous, like so:
myFunction(par1, par2, function() { myFunction_callback(data) });
Notice that the
$(document).ready(function() {});
looks pretty much just like that.
You use the actual name of the function, i.e. myFunction_callback instead of myFunction or anotherFucntion_callback.

Categories

Resources