How to find the function caller in angularjs - javascript

I have build an angularjs application. there are many places I used javascript console functions.
now I want to use a single variable to turn off those console.
I dont want to check the variable everytime whenever I use the console function.
so I decided to make a service to handle that process.
Console factory
AppModule
.factory("$console", function (ENV) {
function log (txt) {
var args = arguments;
if(ENV.debug) {
console.log.apply(this, args);
}
}
...
...
});
And I called that function like the following way.
Controller
AppModule
.controller('CommonCtrl', function ($scope, $console
$scope.personalInfo = function () {
$scope.errmsg = false;
getPersonalInfo(function (data) {
if(!$scope.errmsg) {
$console.log("userdatainfo:",data);
}
...
...
})
});
All is working perfectly.
But Only the problem is I can only see the line number of the factory file on inspect panel.
I need to have the line number from where the factory function is getting called (like the line no of the above controller file).
Please reply with valuable suggestion.

This is a javascript feature and not specifically Angular. You can use arguments in a function like this. However the line number is not given but you get the caller name.
function Hello()
{
console.log("caller is " + arguments.callee.caller.toString());
}

Related

Why does Node think this isn't a function but javascript is fine sometimes?

I have a larger project I'm working on that's calling a Lambda in AWS via an API Gateway that I've configured. In the Lambda I'm trying to dynamically call a variable based on a query string param on an API request by using the following:
var functionToCall = event.queryStringParameters.tech;
console.log("functionToCall is " + functionToCall);
global[functionToCall](event, output);
Unfortunately I get an error of
TypeError: global[functionToCall] is not a function
I've rewritten this using window to demonstrate it online and depending on whether I run it in jsbin or jsfiddle I get different results. The following works in jsbin:
'use strict';
var functionArray = ["one", "two", "three"];
var randFunction = functionArray[Math.floor(Math.random() * functionArray.length)];
function one() {
console.log("function one called");
};
function two() {
console.log("function two called");
};
function three() {
console.log("function three called");
};
console.log(randFunction);
window[randFunction]();
When I run it in jsfiddle I get
Uncaught TypeError: window[randFunction] is not a function
at window.onload (VM99:49)
Ultimately I'm looking for some help in running this in my Lambda(node.js) as it'll make things easier and also help me be DRY.
Thanks!
In Node.js, each module has its own scope, and you never get implicit globals.
Instead of relying on strings and globals, you should make an array of functions directly:
var functions = [
function() {...},
function() {...},
function() {...}
];

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.

Javascript Functions Inside Parameters?

I come from a background in C/C#/Java and PHP so I'm used to those standards of coding, where a function is defined using function(parameters) { ... return x}
But lately I've been learning some JS libraries like Angular/Node and come across functions (or maybe there not?) with another function inside the parameters, like this:
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}]);
app.factory('forecast', ['$http', function($http) {
return $http.get('https://s3.amazonaws.com/codecademy- content/courses/ltp4/forecast-api/forecast.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
It just confuses me and goes against what I've learned about functions. Is this convention only used in scripting languages? I seems like they go
function(parameter, function(parameter) { do something; });
Anyone explain why this is used or if it does anything than a normal function?
Thanks.
In Javascript a variable can return a function, which could return another function, pretty much endlessly.
For example:
var myFunction = function() {
return getAnswer();
}
var getAnswer = function() {
return "Hello world!";
}
console.log(myFunction); will return
var myFunction = function() {
return getAnswer();
}
and console.log(myFunction()); will return
"Hello world!"
So App.controller is a variable that is part of the app object, but it's a function so you are passing in parameters, some of which can be a function.
https://jsfiddle.net/Lu46sf2v/2/
Is a way of passing a function as an argument to another function. In C, you can define a function, and then pass it to another function as a pointer. In Javascript, you can just define the function right there. C# can do that too.
In javascript, functions are first-class objects, meaning you can attach parameters to them, rename them, create them on the fly, or pass them like normal objects.
In node.js, for instance, most libraries specify a function to call after some operation completes. You can either point it to an existing function by name, or you can make an anonymous one and stuff it into the parameters.
In Javascript, functions are first-class functions, this means you can pass a function as an argument, or return a new function inside a function.
What you're seeing is a callback, you receive that function as an argument and execute sometime later when you need.
E.g: A function that will be called when you click at a button
var btn = document.querySelector('btn');
btn.addEventListener('click', function() {
alert("I was clicked");
});
This code will add a listener to the button, when the click is fired it'll call the callback function.

Know every function on scope

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.

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.

Categories