javascript function running without being called - javascript

I wonder why, as soon as the page loads, the function btw_bijtellen () is called. I wanted to call it by clicking...
var $ = function (id) {
return document.getElementById (id);
}
function btw_bijtellen () {
window.alert("we want to calculate something after clicking th button");
}
$("bereken").onclick = btw_bijtellen ();

You've added () which causes the function to execute.
For example:
var myFunc1 = function() {
alert('Hello');
}(); // <--- () causes self execution
var myFunc2 = function() {
return 5 + 5;
};
var some_value = myFunc2(); // <--- Again () causes execution (you'd expect this one)
In your case, as mentioned in comments you're basically telling the onclick to set its value to the return value of the function.
If you drop the () it should run as expected.

If you want the function to be called on click then use
$("bereken").on('click', btw_bijtellen);
Update (As per query from WAO)
If you need to pass the argument, then you need to specify as the second argument. the $.on() gets the data in the event handler
$("bereken").on('click', {key1: value1, key2: value2, keyn: valuen}, btw_bijtellen);
where, you can get your parameters from event.data
var function = btw_bijtellen(event) {
var data = event.data;
console.log(data);
var key1 = event.data.key1;
console.log(key1); // this will output value1
}
Have a read on this link jQuery $.on() api

Putting () after a function name is how you call it.
If you want to assign the btw_bijtellen to onclick then remove the () from the last line of the code in the question.
With the () there, you are calling the function and assigning its return value to onclick. Since that function has no return statement, that value will be undefined which is not what you want.

Related

How to create a javascript functional 'class' so that I can access a 'method' from outside and inside the function

I am creating a function that handles a bunch of stuff around pagenating and sorting a table. It contains a key function that submits the db query and updates the display table.
I want to be able to access that inner function/method from both inside the function and also from outside on the object created.
testFunction = function() {
keyMethod = function() {
console.log('ya got me');
};
document.getElementById('test').addEventListener('click', function (e) {
keyMethod();
});
keyMethod();
};
myTest = new testFunction();
myTest.keyMethod();
testFunction = function() {
this.keyMethod = function() {
console.log('ya got me');
};
document.getElementById('test').addEventListener('click', function (e) {
// would have to use bind here which then messes up trying to
// find the correct target etc.
keyMethod();
});
this.keyMethod();
};
myTest= new DrawShape();
myTest.keyMethod();
Creating it the first way means that the keyMethod function is available everywhere within the testFunction but I cant call it from outside.
Creating it the second way means I can do myTest.keyMethod but I then cant call it from within an inner function without using bind everywhere.
Is there a better way..?
You could replace the function provided as callback with an arrow function or use bind the function first like you already said.
testFunction = function() {
this.keyMethod = function() {
console.log('ya got me');
};
// Replace callback by simply providing the function to call.
// This works as long as you don't use the `this` keyword inside the
// provided function.
document.getElementById('test').addEventListener('click', this.keyMethod);
// If your callback method does use the `this` keyword you can either use an
// arrow function or bind the function up front.
document.getElementById('test').addEventListener('click', event => this.keyMethod());
document.getElementById('test').addEventListener('click', this.keyMethod.bind(this));
this.keyMethod();
};
console.log("constructor output:");
myTest = new testFunction();
console.log(".keyMethod() output:");
myTest.keyMethod();
console.log("click event output:");
<button id="test">test</button>

function create button with a passing argument onclick function

Can someone explain me like i'm five why is it executing the function without the click event. And how to fix it. Thanks.
function test(){
alert("works");
}
function createButton(name,location,id,funX){
var button = document.createElement("input");
button.type = "submit";
button.name = name;
button.id = id;
button.onclick = funX;
var placeHolder = document.getElementById(location);
placeHolder.appendChild(button);
};
window.onload = function () {
createButton("Submit","content","submitEnd",test());
};
http://jsfiddle.net/mabui91/yLoty39s/
When you add parenthesis to a function, you call it. Not later, but right then and there, and you return what ever the function returns.
A function in javascript returns undefined by default, unless you explicitly return something else.
What you're really writing is
createButton("Submit", "content", "submitEnd", undefined);
The last undefined is because you called the function, it would be the same as
var result = test(); // undefined
createButton("Submit", "content", "submitEnd", result);
The way to solve it, is to reference the function, not call it
createButton("Submit", "content", "submitEnd", test);
See, no parenthesis.
FIDDLE

How to determine if a function has been called without setting global variable

I am looking for a good technique to get away from what I am tempted to do: to set a global variable.
The first time someone runs a function by clicking a button it triggers an initial function to turn a few things into draggables. Later, if they click the button a second time I want to determine if the init function has been initialized, and if so to not call it again. I could easily do this by setting a global variable from the init function and then checking that variable from the click function, but I'm wondering how to do this without setting a global variable. I would really like an example of a way to do this.
You could add a property to the function:
function init() {
init.called = true;
}
init();
if(init.called) {
//stuff
}
While #Levi's answer ought to work just fine, I would like to present another option. You would over write the init function to do nothing once it has been called.
var init = function () {
// do the initializing
init = function() {
return false;
}
};
The function when called the first time will do the init. It will then immediately overwrite itself to return false the next time its called. The second time the function is called, the function body will only contain return false.
For more reading: http://www.ericfeminella.com/blog/2011/11/19/function-overwriting-in-javascript/
Why don't you just check to see if your draggables have a class of draggable on them?
if ($('.mydiv').is('.draggable')) {
//do something
}
Function.prototype.fired = false;
function myfunc() {
myfunc.fired = true;
// your stuff
};
console.log(myfunc.fired) // false
myfunc();
console.log(myfunc.fired) // true
What you could do is unhook the init function from the prototype.
​var Obj = function () {
this.init = function () {
document.write("init called<br/>");
this.init = null;
}
}
var o = new Obj();
if (o.init) document.write("exists!<br/>");
o.init();
if (o.init) document.write("exists!<br/>");
o.init();
​
The first if will be true and print exists! but since the function removes itself, the second if will fail. In my example, I call the second init unconditionally just to show that nothing will happen, but of course you could call it only if it exists:
if (o.init) o.init();
http://jsfiddle.net/coreyog/Wd3Q2/
The correct approach is to use the Javascript Proxy APIs to trap the function calls using apply handler.
const initFun = (args) => {
console.log('args', args);
}
const init = new Proxy(initFun, {
apply(target, thisArg, args){
target.calls = target.calls ? target.calls + 1 : 1;
return target.apply(thisArg, args);
}
});
init('hi');
console.log(init.calls); // 1
init('hello');
console.log(init.calls); // 2

usage of javascript closure function

I am trying to figure out how to work with a closure function.
On a click event, I want to determine values of parm1 and parm2 and display them in a div,
then update new values to an table with an SQL statement.
If user clicks repeatedly, I want to throttle (debounce) and only perform SQL update 5 seconds after user stops clicking. However, display of parm1 and parm2 should occur on each click.
I am unsure of how to pass the parms to the SQL process.
(function() {
// create debounced function
var d_process = $.debounce(SQLprocess, 5000);
$('#myButton').click(function() {
// determine parameters
var parm1 = 1 + 1; // edit: added var
$(".div_1").text(parm1);
var parm2 = 2+2; // edit: added var
$(".div_2").text(parm2);
d_process();
});
}());
function SQLprocess(parm1, parm2) {
//perform an SQL update
}
Reference:
http://code.google.com/p/jquery-debounce/
To pass SQLprocess with parameters to the debounce function, change this:
var d_process = $.debounce(SQLprocess, 5000);
to this:
var d_process = $.debounce(function() {SQLprocess(parm1, parm2)}, 5000);
This creates an anonymous function with no parameters that is passed to debounce. But that anonymous function calls SQLprocess with the right parmeters.
Some people ask why you can't do this:
var d_process = $.debounce(SQLprocess(parm1, parm2), 5000);
The answer is because, in the Javavscript language, SQLprocess(parm1, parm2) is a function call. It will execute that function immediately and pass the return value to $.debounce() which is not what you want. $.debounce is expecting a function with no arguments so that's what you have to pass it. The way to get your arguments to SQLprocess is to wrap that in a function that has no arguments. It does not have to be an anonymous function. It could also be like this with a named function if you want:
function myFunctionWrapper() {
SQLprocess(parm1, parm2);
}
var d_process = $.debounce(myFunctionWrapper, 5000);

Javascript's object.onClick runs the function instead of setting onClick, how can I prevent that from happening and only execute the function onClick?

I have the following code:
function sdefaults()
{
alert("test");
}
var btnpos, sbtn;
btnpos = document.getElementsByName('somePosition')[0];
sbtn = document.createElement('input');
btnpos.parentNode.insertBefore(sbtn, btnpos.nextSibling);
sbtn.type = "button";
sbtn.name = "social";
sbtn.value = "Defaults";
sbtn.onClick = sdefaults();
The button appears where I want it to and the name/value are set correctly. However when I load the page, the sdefaults() function is run and then if I click the button, nothing happens. Could anyone provide any insight into how to prevent the function from running on load and force it to only run onclick?
Thanks
Change:
sbtn.onClick = sdefaults();
to:
sbtn.onClick = sdefaults;
sbtn.onClick = sdefaults(); means: "Run the sdefaults function and store the result in sbtn.onClick.
btn.onClick = sdefaults; means: "Set sbtn.onClick to the function sdefaults", which is what you're looking for.
You have to understand the difference between function referencing, and function invocation.
Consider the following function
function foo()
{
alert( 'Hello World' );
}
Now, lets look at some samples of referencing this function. To reference a function, we use its symbol name, just like any other variable.
// Alert contents of foo
alert( foo );
// Set foo as the click handler for the body
document.body.onclick = foo;
// Assign a new function to foo
foo = function(){ alert( 'Goodbye!' ); }
Now we'll consider function invocation. This means the function executes and its return value is sent back to the calling scope.
// Invoke foo simply
foo();
// Invoke foo with a specific scope
foo.apply( this ); // or foo.call( this );
Now, it's entirely possible to modify your code snippet just by changing the code of sdefaults(). Here's how that would look.
function sdefaults()
{
return function()
{
alert("test");
}
}
Now, when you execute sbtn.onClick = sdefaults(); what happens is the onClick property receives what its expecting, a function, since we've modified sdefaults to not actually alert "test", but to return an anonymous function which itself will alert "test". (As a side note, this specific technique is commonly called a lambda or delegate function)
Hope that clears it up.

Categories

Resources