How to / can you call functions inside of another function? - javascript

So the basic setup of the function I want to access is
(function (self, $) {
function init() {
...
}
function stuff() {...
}
self.onload = init;
}
})(window, jQuery);
So if possible how would I call any of these functions from the console? For example I want to do
stuff("things");
One of my ideas to access this is to completely remove the function wraping the game code and running init myself, but I wasn't sure how to get my code to replace the code already on the page.

Your functions are inside a closure you'd have to make them global or accessible from a global object to make them accessible from the console straight away. e.g.
var myprogram = (function (self, $) {
function init() {
...
}
function stuff() {...
}
self.onload = init;
return {
stuff: stuff
};
})(window, jQuery);
now you could call myprogram.stuff() from the console. However I wouldn't recommend this break in encapsulation if your not doing it for testing.
You can also set break points using your debbuger and then call them from the console, which would be my recommendation, see the links below for more information.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger
https://developer.mozilla.org/en-US/docs/Tools/Debugger

For debugging purposes, you could add the functions to the window scope like so:
(function(self, $) {
function stuff() {
...
}
window.stuff = stuff; // Remove this line in production
})(window, jQuery);
Now you can call stuff() from the console.

Related

overriding fullcalendar javascript functions which is in another script

I am newbie in js and I want to override/overwrite some fullcalendar functions from another script (my-fullcalendar.js) to make some changes in it for myself. for example function names are :
formatRange and oldMomentFormat.
formatRange is accessible from this.$.fullCalendar.formatRange but oldMomentFormat is not accessible via this kind of chain. But even when I do something like this in my-fullcalendar.js:
;(function () {
function MyformatRange(date1, date2, formatStr, separator, isRTL) {
console.log( "MyformatRange");
//other parts is exactly the same
// ...
}
this.$.fullCalendar.formatRange=MyformatRange;
console.log(this);
})();
nothing happens because no log is generated and even line by line tracing does not pass from here. but when observing "this" in console log MyformatRange replaced by original formatRange.
another problem is how can I override/overwrite oldMomentFormat function which is not in window hierarchy to access (or I can not find it) ??
OK, let's simplify the problem. In essence, you have this situation:
var makeFunObject = function () {
var doSomething = function (msg) {
console.log(msg);
};
var haveFun = function () {
doSomething( "fun!");
};
return {
doSomething : doSomething,
haveFun : haveFun
};
};
In other words you have a function that is creating a closure. Inside that closure are two "private" functions, one of which calls the other. But both functions seem to be "exposed" in the returned object.
You write some code:
var myFunObject = makeFunObject();
myFunObject.haveFun(); // fun!
Yep, seems to work just fine. Now let's replace the doSomething function in that returned object and call haveFun again:
myFunObject.doSomething = function (msg) {
console.log("My new function: " + msg);
};
myFunObject.haveFun(); // fun! <== wait what?
But wait! The new replacement function is not being called! That's right: the haveFun function was expressly written to call the internal function. It in fact knows nothing about the exposed function in the object at all.
That's because you cannot replace the internal, private function in this way (you cannot replace it at all, in fact, not without altering the original code).
Now draw back to the FullCalendar code: you are replacing the external function in the object, but the internal function is the one that is called by every other function inside FullCalendar.
I realize this is an old question, but I was butting my head against this same problem when I wanted to override the getEventTimeText function.
I was able to accomplish this, from inside my own JS file, like so:
$.fullCalendar.Grid.mixin({
getEventTimeText: function (range, formatStr, displayEnd) {
//custom version of this function
}
});
So, in terms of the function you were trying to override, you should be able to do it with:
$.fullCalendar.View.mixin({
formatRange: function (range, formatStr, separator) {
//custom formatRange function
}
});
Note: Make sure this runs before where you actually create the calendar. Also note that you need to make sure to override the function in the right place. For example, getEventTimeText was in $.fullCalendar.Grid, while formatRange is in $.fullCalendar.View.
Hopefully this helps other people who end up on this question.

How to Call this JavaScript Method which is Wrapped in a jQuery Function

I am studying a JavaScript file and saw in it that some of the methods are wrapped inside a jQuery function. Can Anyone help me how to invoke the following method? And may I know what is the advantage or why the method is wrapped in a function? Below is my sample JavaScript code.
JQuery/JavaScript
$(document).ready(function () {
//How to invoke "testMethod" method?
$(function () {
function testMethod() {
alert("this is a test method");
}
});
});
As you've declared it, testMethod() is a local function and is only available inside the function scope in which it is declared. If you want it to be callable outside that scope, you will need to define it differently so that it is available at a broader scope.
One way of doing that is to make it a global function:
$(document).ready(function () {
//How to invoke "testMethod" method?
$(function () {
window.testMethod = function() {
alert("this is a test method");
}
});
});
testMethod(); // available globally now
It could also be attached to a global namespace or it could be defined at a higher scope where it would also solve your problem. Without specifics on your situation, we can't suggest which one would be best, but the main thing you need to do is to change how the function is declared so it is available in the scope in which you want to call it from.
P.S. Why do you have one document ready function nested inside another? That provides no extra functionality and adds unnecessary complexity. Also, there's really no reason to define testMethod() inside your document ready handlers if you want it available globally.
Before anything else:
$(document).ready(function(){...});
//is the same as
$(function(){...}}
As for your question, here's are potential ways to do it:
If that function is some utility function that everyone uses, then have it available to all in some namespace, like in this one called Utility:
//Utility module
(function(ns){
//declaring someFunction in the Utility namespace
//it's available outside the ready handler, but lives in a namespace
ns.someFunction = function(){...}
}(this.Utility = this.Utility || {}));
$(function(){
//here in the ready handler, we use it
Utility.someFunction();
});
If they all live in the ready handler, and want it to be used by all code in the handler, have it declared in the outermost in the handler so all nested scopes see it.
$(function(){
//declare it in the outermost in the ready handler
function someFunction(){...}
//so we can use it even in the deepest nesting
function nestedSomeFunction(){
someFunction();
}
someElement.on('click',function(){
$.get('example.com',function(){
someFunction();
});
});
nestedSomeFunction();
someFunction();
});
Your call needs to be within the $(function.
It's all about scope and you need to break the testMethod out of the $(function.
Can you perhaps further explain your requirement so that we can maybe help a little better?
Into ready event:
$(document).ready(function () {
//How to invoke "testMethod" method?
var testMethod = function () {
alert("this is a test method");
}
// V0.1
testMethod();
// V0.2
$('#some_id').click(testMethod);
});
In other part:
myObj = {testMethod: null};
$(document).ready(function () {
//How to invoke "testMethod" method?
myObj.testMethod = function () {
alert("this is a test method");
}
});
// Something else
if( myObj.testMethod ) myObj.testMethod();

Firebug and self-invoking anonymous functions

My basic setup is a whole heap of Javascript under an anonymous self-invoking function:
(function () {
...
})();
My problem is that I can't seem to get access to the objects within this ASI function via the DOM tab. I tried both the following:
var MYAPP = function () {
...
};
var MYAPP = (function () {
...
})();
The first didn't fire at all. The second just said MYAPP is undefined in the DOM tab.
Is there a way around this?
In your first version, you are simply creating a function with the name MYAPP, but you are not executing it.
In the second version, your function is executed and its result is assigned to MYAPP. But your function does not seem to return anything, so MYAPP stays undefined.
See A Javascript Module Pattern on YUIBlog for an explanation of this pattern. Their example goes like this:
YAHOO.myProject.myModule = function () {
return {
myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty.",
myPublicMethod: function () {
YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");
}
};
}(); // the parens here cause the anonymous function to execute and return
So your function basically returns an object containing all the public members. You can then access these with Firebug, too.

Calling External function from within function - Javascript

I am using Phonegap and JQueryMobile to create a web application. I'm new to javascript and am having an issue.
My issue is with calling a function I have in a file named "testscript.js", the function is called testFunc. The testscript.js containts only this:
function testFunc() {
console.log("Yes I work");
}
Within my html page I have the following code:
<script>
$('#pageListener').live('pageinit', function(event)
{
testFunc();
});
</script>
The test function is found within my "testscript.js" which I am including with this line within the head tags:
<script src="testscript.js"></script>
The error I get is a "testFunc is not defined".
I am assuming its some type of scope issue as I'm able to call other jquery functions such as:
alert("I work");
and I am able to call my functions by sticking them within script tags in the html elsewhere.
I've tried all sorts of ways of calling my function with no success, any help is appreciated!
You must include the testscript.js before the other jquery code in your html. Like this:
<script src="testscript.js"></script>
<script>
$('#pageListener').live('pageinit', function(event)
{
testFunc();
});
</script>
As long as testscript.js has been loaded by the time PhoneGap fires the pageinit event, and provided the testFunc function is a global, there's no reason that shouldn't work.
You haven't shown us your testFunc, but my guess is that it's not a global, but rather you have it inside something like, for instance:
$('#pageListener').live('pageinit', function(event)
{
function testFunc()
{
// Do something here
}
});
or just a scoping function
(function()
{
function testFunc()
{
// Do something here
}
})();
Either way, since it's declared within another function, it's local to that function, not global. To call it from another script file, you'll need to be able to get at it from the global namespace (sadly). The best way to do that is not to make it a global, but to create just one global that you'll put all of your shared stuff on, like this:
(function()
{
if (!window.MyStuff)
{
window.MyStuff = {};
}
window.MyStuff.testFunc = testFunc;
function testFunc()
{
// Do something here
}
})();
...which you call like this:
$('#pageListener').live('pageinit', function(event)
{
MyStuff.testFunc(); // Or: window.MyStuff.testFunc();
});

Make a function accessible outside of a closure

Is there a way to make function created inside a closure accessible outside of the closure? I'm working with an AIR app and I need to provide access to the specialFunction() to AIR but the closure is keeping that from happening.
(function () {
... a bunch of code ..
function specialFunction() {
.. some code
}
}());
You can assign the function to the global object (which is window in browsers):
(function () {
... a bunch of code ..
window.specialFuncton = function() {
.. some code
}
}());
This makes it globally available.
If the AIR application also needs access to other functions, then it is better to create a namespace for these functions:
var funcs = {}; // global
(function () {
... a bunch of code ..
funcs.specialFuncton = function() {
.. some code
}
}());

Categories