call a function inside a function from another function - javascript

I'm using jquery and in my app.js file I have tow main functions:
$(document).ready(function (){});
$(window).on("load", function (){});
my code looks like this:
$(function () {
// code
// code
function myFunction(){
// code
}
});
$(window).on("load", function () {
// I want to use myFunction() here but I cant because it's not accessible from here
myFunction();
});
is there a way to do this?

window.lib = {
onWindowLoad: function () {
...
},
onDocReady: function() {
...
},
evenmore: {
nested: function(){
...
}
}
}
$(window).on("load", function () {
lib.onWindowLoad();
});
There would be many other ways to do so.
In case, if you need to read something somewhere, that's here

Related

JavaScript namespace and calling function from two places

I've picked up some JavaScript to work on as follows (very much simplified!)
var namespace = {
init: function (config) {
// do stuff, all ok so far
},
events: function () {
$('#id').on('click', '.class', function (event) {
alert('hello')
}
}};
What I am trying to figure out is how, from the init: block of code, can I call the code in the click event that does alert('hello')?
I realise moving the alert('hello') into a function would help (so I can call the function from init and click), but how would I define the function in this namespace and call it from two places?
What I'm aiming at, and guessing the solution is something like this:
var namespace = {
init: function (config) {
// do stuff
hello
},
hello: function() {
alert('hello');
},
events: function () {
$('#id').on('click', '.class', function (event) {
hello
}
};
I will have to pass event param from click into hello.
I'm still trying to figure out how namespaces work in js... Thanks for any help offered.
Use the this keyword.
var namespace = {
init: function (config) {
// do stuff
this.hello();
},
hello: function() {
alert('hello');
},
events: function () {
$('#id').on('click', '.class', function (event) {
this.hello();
}.bind(this));
}
};
Example of how to use it:
namespace.init();
namespace.events(); // then do a click on the html where you have the class "class"
You can use one of the powerful functionality of Javascript - Closures. Refer the Closures topic in this MDN Documentation.
var namespace = (function(){
function hello(){
alert("hello");
}
return {
init: function (config) {
console.log("called init");
hello();
console.log("called hello from init")
},
events: function () {
$('#but').on('click', function (event) {
hello();
console.log("called hello from events")
});
}
}
})();
namespace.init();
namespace.events();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="but">Click</button>

How do I execute a function once per page refreshing?

I have a code like this:
function myfunc () {
alert('executed');
}
$('.classname').on('click' function () {
myfunc();
});
I want to run myfunc once. I mean I don't want to execute it every time when user clicks on .classname element. I guess I need to warp function-calling into a condition. Something like this:
if ( /* that function never executed so far */ ) {
myfunc();
}
How can I do that?
The simplest way with jQuery is to use .one
function myfunc() {
alert('executed');
}
$('.classname').one('click', function() {
myfunc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="classname">click here!</button>
You should remove the event listener in the function you're calling:
function myfunc () {
alert('executed');
$('.classname').off('click', myfunc);
}
$('.classname').on('click', myfunc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='classname'>Click Me</div>
Don't set a global variable like the other posts describe - there's no need for that and then you're still doing an unnecessary function call. This ensures the function is never called again and the event isn't being listed for.
$( document ).ready(function() {
var hasBeenExecuted = false;
function myfunc () {
alert('executed');
hasBeenExecuted = true;
}
$('.classname').on('click' function () {
if(!hasBeenExecuted){
myfunc();
}
});
});
var functionWasRun = false;
function myfunc () {
functionWasRun = true;
alert('executed');
}
$(document).ready(function() {
$('.classname').on('click', function () {
if (!functionWasRun) {
myfunc();
}
});
});
I would suggest, as an alternative to a global variable, assigning a property to the function.
function myfunc () {
alert('executed');
myfunc.executed = true;
}
$('.classname').on('click', function () {
if(!myfunc.executed) {
myfunc();
}
});
This has the advantage of working the same way while not polluting the global scope unnecessarily. However, if skyline3000's answer works for you, you should use that instead as it's cleaner and more sensible overall.

load a function from jquery defined from external js file

I am trying to do this but it give me an undefined function
$(function () {
function Test(){
Test1();
}
Test1();
});
external.js
$(function () {
function Test1(){
alert("HI");
}
});
how can I avoid the Test1() is undefined error ??
Make the function globally:
$(function () {
window.Test = function(){
Test1();
}
Test1();
});
also make sure Test1has been defined somewhere else!
Your "Test1" function is local to a anonymous function, cannot be visible outside that function. So you need put "Test1"'s definition global.
function Test1() {
//...
}
Don't put this in another function or
window.Test1 = function() {
//...
}
try to change you external.js file from
$(function () {
function Test1(){
alert("HI");
}
});
to
function Test1(){
alert("HI");
}
it has no sense to wrapping Test1 function into on-load

Calling a function (ex. namespace.show) by name

I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/

Is anything wrong with my JavaScript format?

I'm on a .NET MVC2 project and have a reference to SomeClass.Home.js and jQuery in the masterpage. My SomeClass.Home.js looks like this:
SomeClass.Home = {};
$(document).ready(function () {
SomeClass.Home.SomeMethod();
});
SomeClass.Home.SomeMethod= function () {
alert("hello");
};
The call to SomeClass.Home.SomeMethod doesn't work (I don't get the alert). However, if I change it to this, it works, and I get the alert:
$(document).ready(function () {
SomeMethod();
});
function SomeMethod () {
alert("hello");
};
Is anything wrong with the syntax of the first one?
The problem seems to be in the way you described the SomeClass variable. The following code works for me.
var SomeClass = {};
SomeClass.Home = {};
SomeClass.Home.SomeMethod = function() {
alert("hello");
};
$(document).ready(function () {
SomeClass.Home.SomeMethod();
});
Yes, because you're not declaring the method. I believe you should do it like this:
SomeClass.Home = {
SomeMethod = function(){ //stuff });
}
$(function(){ SomeClass.Home.SomeMethod() });
What if you embed the function in the class?
SomeClass.Home = {
SomeMethod= function () {
alert("hello");
};
};
$(document).ready(function () {
SomeClass.Home.SomeMethod();
});
SomeClass.Home.SomeMethod= function () {
alert("hello");
};

Categories

Resources