I have a function called "destination" nested in scrip1.js file. If I add this file at the end of webpage using , how can I trigger it at the next step? Here are some contents of script1.js.
script1.js
$.something = function(element, options) {
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
}
$("body").on("click", ".notify-btn", function (event) {
event.preventDefault();
destination(some args);
});
someOtherFunction();
start();
}
$.fn.something = function (options) {
return this.each(function () {
if (undefined == $(this).data("something")) {
var plugin = new $.something(this, options);
$(this).data("something", plugin);
}
});
};
I tried this, but is not working. Chrome console is showing error about this function.
<script type="text/javascript" src="script1.js"></script>
<script>
$.fn.something().destination();
</script>
I can not change this script1.js, so any possible way?
There's no specific connection between variables declared during function execution - and how the rest of the world sees the result of execution. So this code:
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
}
start();
... lets destination value (remember, functions in JS are first-class citizens) go away when start() completes its execution. That's actually quite convenient if you want to encapsulate some implementation details and hide it from users; this technique (also known as Module pattern) was often used in pre-class world to implement private properties in vanilla JavaScript.
However, all the values returned from a function can be reused. For example, here...
$.something = function(element, options) {
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
return {
destination
};
}
return start();
}
... you make destination function a part of object that is returned from start(). Now $.something returns an object, too; that means it can be reused:
var plugin = new $.something(this, options);
// ...
plugin.destination('some', 'args');
If you're afraid changing the return value might hurt someone, you can try to assign value of destination to $.something object itself as its property, like this:
$.something = function(element, options) {
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
return destination;
}
// ...
const destination = start();
$.something.destination = destination;
}
The returned value is not modified, yet function is accessible. Still, that's not actually a good workaround; the biggest issue is that any subsequent calls on $.something will rewrite the value of that function, which might be not a good thing if its execution depends on some scoped variables.
While technically there's a way to fetch destination function code by parsing $.something source code, I really doubt it's worth the effort in your case.
Related
I am creating AngularJS Javascript application in which i have 500/600 function in a single Directive,
Many functions are Inter connected with each other,
flow starts from the On load Event,
I want to know when i run the project,
which functions are being called on Onload Event
and i want to print the same on console,
I google it but i am not able to get anything,
is there any way to find out the functions which is being executed?
Call console.trace('calling on-load') to find stack-trace on on-load function. It would be better to call trace on the last function you expect to be executed to find all other function which has been called before.
You can wrap all your functions into "log wrapper":
var self = this;
function LogWrapper(action){
return function(){
console.log(action.name);
return action.apply(self, arguments);
}
}
//usage:
function ActualFunctionInner(arg1, arg2){
//some logic
}
var ActualFunction = LogWrapper(ActualFunctionInner);
var result = ActualFunction(1, 2);//console: ActualFunctionInner
Second solution is via Proxy:
let handler = {
get(target, propKey) {
var inner = target[propKey];
return function () {
console.log(inner.name);
return inner.apply(this, arguments);
};
}
};
var loggedSelf = new Proxy(self, handler);
var result = loggedSelf.ActualFunction(1, 2);//console: ActualFunction
Just wondering if there is anyway to fire some code when a function is called, without adding the code to the function, for example:
function doSomething(){
//Do something
}
//Code to call when doSomething is called
You can wrap the function :
(function(){
var oldFunction = doSomething;
doSomething = function(){
// do something else
oldFunction.apply(this, arguments);
}
})();
I use an IIFE here just to avoid polluting the global namespace, it's accessory.
Well, yes, it's not actually hard to do. The crucial thing is that a function's name is just an identifier like any other. You can redefine it if you want to.
var oldFn = doSomething;
doSomething = function() {
// code to run before the old function
return oldFn.apply(this, arguments);
// code to run after the old function
};
NB that it's better to do oldFn.apply(this, arguments) rather than just oldFn. In many cases it won't matter, but it's possible that the context (i.e. the value of this inside the function) and the arguments are important. Using apply means they are passed on as if oldFn had been called directly.
What about something like:
function doSomething(){
doSomething.called = true;
}
//call?
doSomething();
if(doSomething.called) {
//Code to call when doSomething is called
}
I know you said you don't want to modify the original function, but consider adding a callback. Then you can execute code based on different results in your function (such as onSucess and onError):
function doSomething(onSuccess, onError){
try {
throw "this is an error";
if(onSuccess) {
onSuccess();
}
} catch(err) {
if(onError) {
onError(err);
}
}
}
Then, when you call doSomething, you can specify what you want done with inline functions:
doSomething(function() {
console.log("doSomething() success");
}, function(err) {
console.log("doSomething() error: " + err);
});
I need for a function to be executable only after an object is defined, I'm currently working in a fascade pattern and one method is dependent on another method. in this case 'addNewLayer' fails because 'setFullMap' hasn't finished executing. is there a solution? I'm using jquery and vanilla js so most any solution would be helpful at this point:
var jen = (function(){
function setFullMap(mapID){
jen.map = new Map(mapID);
}
function setLayer(opt){
//execute code here after jen.map is defined
}
return{
samp: function(id, opt){
setFullMap(id);
addNewLayer(opt);
}
};
})();
Thanks
solution:
var jen = (function(){
function setFullMap(mapID, callback) {
jen.map = new Map(mapID);
if(jen.map){
callback();
}
}
return {
samp: function(id, opt){
setFullMap(id, function(){
addNewLayer(opt);
}.bind(this));
}
};
})();
You will have to pass a callback function to setFullMap, and execute it once the function has completed (at the very end, before the closing }).
var jen = (function(){
function setFullMap(mapID, callback){
jen.map = new Map(mapID);
callback();
}
function setLayer(opt){
//execute code here after jen.map is defined
}
return{
samp: function(id, opt){
setFullMap(id, function() {
addNewLayer(opt);
}.bind(this));
}
};
})();
Do not forget using .bind(this) - it is very important in order to keep the original this in your callback function.
Edit:
Actually that would not work work if the Map constructor is a-synchronous. If you do not have access to the constructor and/or you cannot pass it a callback, then presumably the only (and sad) option would be to use a setTimeout or (easier) setInterval, continuously checking at defined intervals if the operation has been completed, and then fire the callback.
You could use a callback parameter:
function setFullmap(mapId,callback) {
jen.map = new Map(mapId);
callback();
}
....
samp: function(id, opt){
setFullMap(id,function() {
addNewLayer(opt);
});
}
When u dont have a way to manipulate the Map Object then u need to use a loop:
var loop=self.setInterval(function(){
if(jen.map) {
//execute code here after jen.map is defined
console.log(typeof jen.map);
window.clearInterval(loop);
}
},50);
Check jsfiddle:
http://jsfiddle.net/9yv5t/1/
I have checked the docs and it seems that there are various events you could listen to.
For example:
var m = new Map(...);
m.on('load', function () {
//execute code when the first layer is ready
});
var l = new Layer(...);
l.on('load', function () {
//execute code when the layer has been initialized
});
It's also carefully stated for the Layer.load event:
fires after layer properties for the layer are successfully populated.
This event must be successful before the layer can be added to the
map.
How can i overload the calling process of any function?
In my web app i want to do something before the call of a function and something after it how can i do this without prototyping the call method ( because i tried this and it will work only if i call a function as myFunction.call() ) and still have the requested effect.
I have tried everything for making it work, but nothing works, and to do it the hard way ( by call method ) it's non-practicable because i would have to rewrite all my code.
Could someone help please?
You can change each function definition manually.
You can change each function call manually.
If either of these refactorings is out of the scope of your problems then you're in a spot of bother.
There is no generic way that I'm familiar with to solve your problem.
However if your functions are globally accessible or namespaced then you can do the following quite easily (and can make it much more generic by parametrising the pre and post functions etc.):
NS = {
foo : function(){ console.log('foo'); },
bar : function(){ console.log('bar'); }
};
// <-- new code goes here
NS.foo();
NS.bar();
// new code below, that should go after definitions but before the calls
(function(){
var pre = function(){ console.log('pre'); },
post = function(){ console.log('post'); };
for (var fn in NS) {
NS[fn] = (function(fn){ return function(){ pre(); fn(); post(); }; })(fn);
}
})();
You can create a caller function that accept the function name, the parammeters and the context as parameters:
function pre() {
alert("I'm before the call");
}
function post() {
alert("I'm after the call");
}
function caller(func, parameters, context) {
pre();
func.apply(context, func, parameters.split(','));
post();
}
Or use AnthonyWJones solution on Calling dynamic function with dynamic parameters in Javascript that can be called this way caller(funcName, param1, param2);:
function caller(func){
pre();
this[func].apply(this, Array.prototype.slice.call(arguments, 1));
post();
}
Coming from the Java (OOP) world, I am used to classes, inheritance and multi threading. Now for my little walkabout in the JavaScript domain, I try to utilize these paradigms and patterns where applicable. Read: use prototypes ("classes" / objects) and WebWorkers for parallel execution. However, this one case does not work ...
HTML site starting a worker:
<html>
<head>
<script>
var worker = new Worker("worker.js");
worker.onmessage(event) {
// here be fancy script
}
worker.postMessage("run, worker, run!");
</script>
</head>
...
</html>
Worker called by HTML ("worker.js"):
self.loadScripts("handler.js");
var handler = null;
self.onmessage = function(event) {
if(!handler) {
handler = new Handler();
}
handler.compute();
}
The Handler as called by the worker ("handler.js"):
function Handler() {
}
Handler.prototype = {
compute: function() {
this.doSomething(); // <-- ERROR! "this" points to the worker context,
// not to the Handler instance. So "doSomething" is
// undefined. However, the following line would work:
// Handler.prototype.doSomething();
},
doSomething: function() {
// More code here
}
}
Is JavaScript prototyping and "inheritance" meant to work this way? Should I always use the prototype property instead of this? What if I want to access this.myProperty instead of a function?
Also: is there any reasonable way to bind this to the Handler instance in the constructor? At least the code is not cluttered with lengthy Handler.prototype references.
Thanks!
Thank you for your comments. Indeed, the context of this works as expected. The real code used a timeout callback:
Handler.prototype = {
compute: function() {
self.setTimeout(this.doSomething, 1000); // Here the this got lost
},
doSomething: function() {
// Code here
}
}
It seems this from a timeout call is referencing the worker context. To solve the issue, I just wrapped the callback in an anonymous function (referencing the caller as a variable, as jfriend00 suggested):
Handler.prototype = {
compute: function() {
var caller = this;
self.setTimeout(function() { // Wrap for great justice
caller.doSomething();
} , 1000);
}, doSomething: function() {
// Code here
}
}
Thanks again.