Know every function on scope - javascript

I have a function main that has several inner functions like this:
function main_f (params) {
function do_this () {
// do this...
}
function do_that () {
do_this(); // working
main_f.parse_stuff(); // not working
parse_stuff(); // not working
}
do_that();
main_f.parse_stuff = function(){
console.log("success");
}
}
function second_f () {
main_f.parse_stuff(); //working
}
I was expecting that main_f.parse_stuff() would work inside do_that, but that is not the case. My questions are:
-Is it posible to call that method from inside main_f ? how?
EDIT: Execute do_that after parse_stuff is written.
-Why can't I call parse_stuff from main_f?
EDIT: I just realised that the function doesn't read on compilation time, but execution time, therefore it is not visible when do_that is called.
-How can I know every function on scope?

It is not possible by programation but you can do it with the debugger. Just insert a break point on that scope and you can check everything that is global, local and in the closure.
I checked this with chrome dev-tools.

Related

call function inside method from external js

Please bear with me since I am a newbie in JS programming.
I have the following problem:
One of my modules contains a setInterval loop.
This module is called by my server.js when an HTML button is clicked (ON, variable state in the code). I would like to interrupt its execution (OFF) from the server.js but it doesn't work..
I know it feels like a duplicate question, but I have searched a lot for the info inside Stack Overflow and all questions refer to code being executed and stopped from within the same file. In my case, I am calling a method in an external file (which contains the setInterval) and I want to trigger clearInterval which should be ran in that external file!
Simplified code below:
action.js
module.a = function(milisec) {
var myVar = setInterval( function() { do stuff }, milisec);
}
module.exports = methods;
My first attempt:
Server.js
// var state is a button on my HTML
var actions = require('./actions');
If (state == 1)
{ actions.a(milisec) }
If (state == 0)
{ clearInterval(myVar) }
But it didn't work. And I think it's also clear why: The code has no clue where I got the myVar from, basically I think I should call a function from inside the module to stop the setInterval, therefore, I included the function stop() in the method.
My second attempt:
action.js
methods.a = fuction(milisec) {
var myVar = setInterval( function() {
console.log("I'm being executed");}, milisec);
function stop() {
clearInterval(myVar);
}
}
Module.exports = methods;
But I don't know how to refer to the function inside my methods.a on the server.js file
I've tried:
actions.a.stop()
but it doesn't work at all..
Is it even possible? Is there a way to execute the clearInterval in my server.js?
Appreciate your help
You are declaring myVar inside of methods.a(), making it's scope local to that function. Try declaring myVar outside of the function.

Javascript - Is it possible to make a function call itself after definition and then be referenced as a function elsewhere in scope

Consider the following:
(function () {
var _searchUsers = function () {
console.log("Searching...");
};
var search = (function () {
_searchUsers();
this = function () {
_searchUsers();
}
})();
//Some onclick event handler
function click () {
search();
}
})();
Is there a more concise way of achieving this feature in javascript? I want to declare a function and have it execute straight away and that's why I've made it an IIFE (self executing function) but I also want to reference that function elsewhere in scope later on the in the lifetime of the script, say when a user clicks a button and the "click" function is invoked above.
Example use-case:
I have a table of users, on page load I want to make an AJAX request to go and fetch the users immediately, I also want the user's to be able to load the users at a click of a button, let's say I have a search box which sends that text up to my API and returns user's who's name matches the given text.
The above snippet handles this requirement, I'm just wondering if there is a more concise method to achieve this, and i'm also just interested to see what people post as an answer.
This is another option:
(function () {
var _searchUsers; // Declare the variable like you did already
(_searchUsers = function (){ // Assign the function, and immediately call it.
console.log("Searching...");
})();
//Some onclick event handler
function click () {
_searchUsers();
}
})();
Mostly I see this being implemented like a named IIFE function that returns it self after the execution. So that it can be used later on scope because it is a named function.
(function () {
onClick(function MyFunction(){
// logic code goes here
return MyFunction;
}());
})();

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.

Recognising variables while assigning a function to a variable in javascript

In my jQuery scripts, when the user closes a menu with an animation, I have to call a function after the closing animation is finished. I want to assign this function dynamically by calling a function openStrip() with a parameter. My code looks like:
var FUNCTION_JUST_AFTER_MENU_CLOSE = function(){};
function openStrip(stripId){
FUNCTION_JUST_AFTER_MENU_CLOSE = function(){
createStrip(stripId);
});
}
if I call openStrip("aStripId"), I expect FUNCTION_JUST_AFTER_MENU_CLOSE to be:
// #1
function(){
createStrip("aStripId");
}
whereas my current code gives:
//#2
function(){
createStrip(stripId);
}
i.e, the parameter passed to the function openStrip() is lost while assigning the function() to the variable FUNCTION_JUST_AFTER_MENU_CLOSE.
How can I avoid this.
EDIT: I discovered that my code is actually working. The problem was elsewhere. I got confused because when I looked at Chrome's debugger, it was showing me the function definition as is (#2 in above). But when it actually went down executing that function later in the code, it did evaluate the values of the passed argument, and endedup executing #1.
Thanks for the answer though. I am marking it correct because that is perhaps a better way of assigning the function.
The best way is to return a function, from openStrip like this
function openStrip(stripId) {
return function() {
createStrip(stripId);
};
}
For example,
function openStrip(stripId) {
return function() {
console.log(stripId);
};
}
openStrip("aStripId")();
# aStripId
openStrip("bStripId")();
# bStripId
You can even assign the function objects returned to different variables and use them later on
var aStrip = openStrip("aStripId");
aStrip();
# aStripId
aStrip();
# aStripId

javascript: pass function as a parameter to another function, the code gets called in another order then i expect

i want to pass a function to another function as a parameter.
I want to do that because the latter function calls an async Jquery method and AFTER that gives a result back, i want some javascript code executed.
And because this function is called from multiple places, i want the code to execute (after the async Jquery code gets executed) to be passed in the function.
Makes sense? i hope :)
Now what is see is that the order in which the code is executed is noth what i want.
I've simplified the code to this code:
$('#AddThirdParty').click(function() {
var func = new function() {
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute;
}
Now what i wanted to achieve (or at least what i thought would happen) was that alert4 would fire, then the loadhtml would fire alert1, alert2 and alert3, and then the code would return to alert5.
But what happens is this: alert1, alert2, alert3, alert4, alert5.
Does anyone know what i'm doing wrong and why this is the order in which the code is executed?
It looks like the alert1..alert3 gets executed when i define the new function(), but why doesn't it ALSO get executed when i call it from the LoadHtml function?
$('#AddThirdParty').click(function() {
var func = function() { // NOTE: no "new"
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute(); // NOTE: parentheses
}
Two errors: the syntax for anonymous functions does not include the keyword new; and JavaScript requires parentheses for function calls, even if functions do not take any arguments. When you just say funcToExecute, that is just a variable giving its value in a context where nothing is using that value (kind of like writing 3; as a statement).
You might notice that you already know how to use anonymous functions: you did not write $('#AddThirdParty').click(new function() ...);
$('#AddThirdParty').click(function() {
var func = new function() {
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute;
}
The new keyword creates an object from the function. This means the function (which is anonymous) gets called immediatly. This would be the same as
var foo = function() {
alert("1");
alert("2");
alert("3");
}
var func = new foo();
This means your creating a new object (not a function!) and inside the constructor your alert 1,2,3. Then you alert 4. Then you call LoadHtml which does nothing, then you alert 5.
As for
funcToExecute;
The funcToExecute is just a variable containing a function. It actually needs to be executed.

Categories