In javascript I know we can watch for a property change, but is it possible to watch a function?
If I had a function that evaluates to a boolen
function eval(value) {
return value == 1;
}
Would it be possible to continuously evaluate this function until true?
I know setTimeout could work, but that seems like a hack. Is there a better way?
There are two main possible ways, the first is yours, the setTimeout. The second is a setInterval:
var checkEval = setInterval(function(){eval(value)},1000);
And you could end it using:
clearInterval(checkEval);
replace the function with a wrapper
function something(){
return value==1;
}
(function(window){
var oldSomething = window.something;
window.something = function(){
var result = oldSomething.apply(null,arguments);
if(result===true){
//do what you need
}
return result;
};
})(window);
Related
Hello everyone hope you are well.
I am trying to call a function in my jQuery file and for some reason it doesn't get called if I call it from an if statement. However the same function gets called for when I call it using .click().
The if statement works fine.
Here is my jQuery code.
$(document).ready(function () {
var hello = 1;
if (hello == 1) {
console.log("True");
helloWorld();
} else {
console.log("False");
}
$('#en').click(helloWorld(pathname));
function helloWorld() {
return function () {
console.log("function called");
}
});
});
You're using
var hello==1;
instead of
var hello=1;
When assigning hello variable, you test it if it is equal to 1, not assigning 1 to variable. Just try with:
var hello = 1;
Your function return another function, if you want to call it, this is the correct way:
helloWorld()();
Or
var myFunc = helloWorld();
myFunc();
Your declaration in variable is wrong.
var hello=1;
I was wondering on how to force javascript code to execute synchronously on my own withouth a plugin.
Would the Browser wait until the following variable has a value in order to proceed with the rest of the code?
EDITED :
var result = (function() { /*doSomething*/ }) ();
Since it can be tricky to test this with a debugger maybe one of you know if this can be achieved or not.
Thanks.
The browser will only store the function inside the variable, giving you the possibility to call that function latter by doing something like this :
var result = function() { // BLABLABLA //};
result(); // Calling the function
If you want a self invoking function, you can do this:
var result = (function(){ // BLABLABLA // })();
What are you trying to achieve exactly ?
I believe you're looking for a self-invoking function. It looks like this.
var result = (function(){ /* do something */ }());
// Or...
var result = (function(){ /* do something */})();
This will execute the function immediately and assign the return value to result.
I have this very simple thing, that doesn't work. What is happening? According to the tutorials that I have read, this should output 4...
function sum(a,b) {
var result = a + b;
return result;
}
sum(2,2);
var test = sum();
alert(test); // shouldn't this return "4"?
Link to the JSFiddle
function sum(a,b) {
var result = a + b;
return result;
}
var test = sum(2,2);
alert(test);
Change this:
sum(2,2);
var test = sum();
To this:
var test = sum(2,2);
The first code isn't technically wrong it just isn't doing what you're trying to do. You're calling the sum function with the appropriate values but never setting it's return value to any variable so it just gets thrown away. You seem to be under the impression that the value will "stick" to the function and this isn't the case. (Some BASIC languages can make it seem this way though. Perhaps that's where your misconception is coming from.)
Your second call is essentially the equivalent of
var test = sum(null, null);
and when you concatenate two null values you get null again.
I have a function that I call to retrieve a sliding pane (telerik splitter control)
I thought I could use this function
function getZone() {
var slidingZone = $find("<%= slidingZone.ClientID %>");
return function () { return slidingZone; };
}
so that it didn't have to "find" the sliding zone every time. But it doesn't work.
This does...
function getZone() {
var slidingZone = $find("<%= slidingZone.ClientID %>");
return slidingZone;
}
Can you tell me why the first one isn't working?
BTW, I'm using it like this....
function hideTreePane() {
var paneId = "<%= slidingPane.ClientID %>";
getZone().undockPane(paneId);
return true;
}
Because your returning a function and you need to evaluate it...
If using the first function this may work..
function hideTreePane() {
var paneId = "<%= slidingPane.ClientID %>";
var zoneFunc = getZone();
zoneFunc().undockPane(paneId);
return true;
}
You will need to call the function you are returning from getZone:
getZone()().undockPane( paneId );
It wasn't working because the function getZone itself does not have a member called undockPane.
EDIT:
I think it would be better to do this:
function getZone() {
if ( getZone.cache === undefined )
getZone.cach = $find("<%= slidingZone.ClientID %>");
return getZone.cache;
}
Then you would call like this:
getZone().undockPane( paneId );
Well, the first function, returns a function, and you want the inner function to be executed.
If you invoke the result of it you will see it work, e.g.:
getZone()();
I think you want the following, use an immediately executed anonymous function, to call the $find method only once, storing its result:
var getZone = (function() {
var slidingZone = $find("<%= slidingZone.ClientID %>");
return function () { return slidingZone; };
})();
In your first example you're returning a function, therefore getZone() becomes a function itself and you need to do getZone()() to get the slidingZone value you want.
There's no need to wrap your return value in a function for this case.
You're returning a function from the first example, not a value. You'd need to evaluate the function for it to work. Try something like.
var slidingZone;
function getZone() {
if (!slidingZone) {
slidingZone = $find( ... );
}
return slidingZone;
}
It would be better for this to be part of a "class" so that the caching variable isn't in the global scope.
Ok, this may sound a bit crazy but hear me out :)
I would like to do the following in javascript:
define START_OF_EVERY_FUNCTION = "try {"
define END_OF_EVERY_FUNCTION = "} catch () {}"
function TEST () {
START_OF_EVERY_FUNCTION
// rest of function
END_OF_EVERY_FUNCTION
}
Basically, can I define a list of javascript lines (code) and include them as above? I'm looking for a technique versus comments about whether this is a good idea or not or debate over wrapping all functions in a try/catch block.
I know about eval(), but I dont think you can eval statements like the above.
This might be goofy but you could define a master function and run other functions through it by passing them in.
var execute = function(func){
alert('before');
func();
alert('after');
};
function sayHi(){
alert('hi there');
}
execute(sayHi);
As requested, an example with passing arguments.
var execute = function(func){
alert('before');
var ret = func.apply(null, Array.prototype.slice.call(arguments, 1));
alert('after');
};
function saySomething(sayWhat){
alert(sayWhat);
}
execute(saySomething,'hey there');
That is not allowed in JavaScript.
You could extend the Function prototype:
Function.prototype.tryThis = function() {
try {
this();
}catch(ex){
alert('Caught '+ex);
};
};
function tryIt() {
alert('Inside tryIt');throw "My Error from tryIt";
}
tryIt.tryThis();
You need to look into aspect oriented programming for JavaScript. You can create hooks for function entry and exit. Tools like JSUnit do this for example.
I think you can do this with the "new Function" operator. I've never used it myself, since I'm not clinically insane, but I believe you can pass it a string which it will evaluate and use as the function body. You can also get the code for each function by calling myFunction.toString(). So put together, it'd be something like this:
var functionsToMessUp = ['myFunc1', 'myFunc2'];
for (var i = 0; i < functionsToMessUp.length; ++i) {
var theFunc = window[functionsToMessUp[i]]; // assuming they're in global scope
window[functionsToMessUp[i]] = new Function(
START_OF_EVERY_FUNCTION
+ theFunc.toString()
+ END_OF_EVERY_FUNCTION
);
}
Now, the above almost certainly won't work - there's parameters and other things to take into consideration, and I don't even think that's how the new Function constructor works, but if you really want to go down this path (which I really don't recommend), then this might be a good starting point for you.
Maybe something like this?
function tryCatch(callback) {
try {
callback();
} catch() {}
}
var myFunction = function() {
// do some stuff
};
tryCatch(myFunction);