Set JavaScript variable to check definition later - javascript

How can you set a var to something you want to later check if it's defined or not?
Example: To check if jQuery is not defined, you'd do this:
if (typeof(jQuery) === 'undefined') {
}
But what if I want to do something like this (this obviously doesn't work):
var toCheckLater = jQuery; // This fails.
// Some time later..
if (typeof(toCheckLater) === 'undefined') {
}
What I'm trying to do is dynamically load scripts from an array, but I want to set ahead of time the variable whose definition I'll check for later. And I'd like to avoid a big block of ifs or switch statement. Meaning I'm hoping to find a solution a bit more elegant than:
switch (scriptName) {
case 'jQuery':
if (typeof(jQuery) === 'undefined') {
}
break;
case 'someOtherScriptName':
.
.
.
}
Any ideas?
Thanks in advance.

A function would do:
var toCheckLater = function() { return typeof jQuery == "undefined"; }
// later:
toCheckLater()
You might also use a fabric for such functions:
function getChecker(name) {
return function() {
return typeof window[name] == "undefined";
// alternative:
return name in window; // can be undefined, but the variable exists
};
}
var toCheckLater = getChecker("jQuery");

Use
if (typeof jQuery === "undefined")
to check for undefined.

I don't quite get what you're trying to achieve, but I think you could do something like this
var toCheckLater = typeof jQuery; //if, for example, jQuery is defined you'll get "function"
// Some time later..
if (toCheckLater === 'undefined') {
}

Simply do this:
var scriptName = 'jQuery';
if( !window.hasOwnProperty(scriptName) ){
//jQuery is undefined
}

var checker = function(scriptArray) {
for(var i in scriptArray)
this[i] = i?i:loadScript(i); // make your own loadScript function
}
checker({'jquery','anothercode'});
//access checker.jquery / checker.anothercode
You could use something like this. Create a 'class' that load all the scripts.

You have use the typeof Method
typeof(variable_name) will give you "string", "object", "undefined" or "number" depending on the variable
typeof(jQuery) == "undefined"
is the way to go.

Your array of scripts:
var scripts = ['script1', 'jQuery'];
After loading the scripts you can use the same array and loop through it.
for (var i = 0, n = scripts.length; i !== n; i++) {
if (!window.scripts[i]) {
// falsy
}
}
This assumes that the scripts array references a global variable that the script will expose when loaded.
However, if I understand what you're going for, a better method would be to register a callback for when the appropriate script element is loaded. See these questions for some examples: (1), (2)
Code like this is pretty standard:
function loadScriptAsync(src, callback) {
var script = document.createElement('script'),
place = document.getElementsByTagName('script')[0];
script.type = "text/javascript";
script.async = true;
script.src = src;
script.onload = script.onreadystatechange = function() {
callback();
// clean up for IE and Opera
script.onload = null;
script.onreadystatechange = null;
};
place.parentNode.insertBefore(script, place);
}

Related

Javascript associative array not working on Jquery objects

I am trying to build a associative array parentTds however it's not working the way I would like.
var parentTds = {};
var index = 0;
$.each(clone, function () {
var $currentItem = $(selectedActivities[index]);
var $currentItemTd = $currentItem.closest('td');
console.log($currentItemTd.get(0));
var borderLeft = 0;
console.log(parentTds[$currentItemTd.get(0)]);
console.log(parentTds[$currentItemTd]);
if (typeof parentTds[$currentItemTd.get(0)] === "undefined") {
console.log('NOT OK');
borderLeft++;
parentTds[$currentItemTd.get(0)] = $currentItemTd;
} else {
console.log('OK');
}
index++;
});
For some reason parentTds[$currentItemTd.get(0)] always returns the 1st item stored. I get NOT OK just the 1st time the loop runs whereas I should be getting NOT OK a few more times. I suspect the problem is parentTds[$currentItemTd.get(0)] itself.
Any ideas please?
Javascript is not as forgiving as for example PHP. When you use this:
if (typeof parentTds[$currentItemTd.get(0)] === "undefined") {
$currentItemTd.get(0) might be evaulated as 0 and therefore the reference is always parentTds[0]
In these circumstance I use to break up the code-block and do something like this:
var cig = $currentItemTd.get(0);
if (typeof parentTds[cig] === "undefined") {

Closure for static values in Javascript

I have a question. We all know the power of closures in Javascript and I want to use this power. Lets say I have a an object named "BRB". WHat I wanted to is whenever user calls the method getBrowser() for the very first time it will find out browser version/name whatever and return it and also store it inside itself as static when getBrowser() called second time it should return the same value without calculation since it is already statically stored somewhere. This can be done in many different ways, we can just store a property in the object and in the first call we can set some values for it and use it later, we can run getBrowser method directly when object is created in the syntax as
(function()(
...
))()
However, this is not what I want. All I want is getBrowser() method to calculate the value only once and use it all the time, I dont want to store the value inside the object somewhere else and I dont want to run this method right away when object is created, I'm allowed to use only and only this method and all action must take place in this one method. I put here an example, as you see it will always print out "0" but what I want is it prints 0,1,2,3 for each console.log request. I hope I made myself clear. Thanks.
(
function(window){
if(window.BRB) return;
var BRB = function(){}
BRB.prototype.getBrowser = function(){
var browser = null;
return function(){
if(browser === null){
browser = 0;
}
return browser++;
}
}
window.BRB = new BRB();
})(window);
console.log(BRB.getBrowser()());
console.log(BRB.getBrowser()());
console.log(BRB.getBrowser()());
console.log(BRB.getBrowser()());
Your requirements are kinda strange. Is this what you're looking for? It works by creating a property on the getBrowser function itself:
(function(window){
if(window.BRB) return;
var BRB = function(){}
BRB.prototype.getBrowser = function(){
if(typeof this.getBrowser.browser == "undefined"){
return this.getBrowser.browser = 0;
} else {
return ++this.getBrowser.browser;
}
}
window.BRB = new BRB();
})(window);
console.log(BRB.getBrowser());
console.log(BRB.getBrowser());
console.log(BRB.getBrowser());
console.log(BRB.getBrowser());
http://jsfiddle.net/5DheZ/
You should define the browser variable in another place:
(
function(window){
if(window.BRB) return;
var browser = null;
var BRB = function(){}
BRB.prototype.getBrowser = function(){
if(browser === null){
browser = 0;
}
return browser++;
}
window.BRB = new BRB();
})(window);
console.log(BRB.getBrowser());
console.log(BRB.getBrowser());
console.log(BRB.getBrowser());
console.log(BRB.getBrowser());
jsfiddle http://jsfiddle.net/5ByYR/1/
And if you are able to assign an object instead of function to getBrowser:
(
function(window){
if(window.BRB) return;
var BRB = function(){}
BRB.prototype.getBrowser = {
browser: null,
get: function() {
if(this.browser === null){
this.browser = 0;
}
return this.browser++;
}
}
window.BRB = new BRB();
})(window);
console.log(BRB.getBrowser.get());
console.log(BRB.getBrowser.get());
console.log(BRB.getBrowser.get());
console.log(BRB.getBrowser.get());
You probably intended for the getBrowser method to be an IIFE closure for the result:
BRB.prototype.getBrowser = (function(){
var browser = null;
return function(){
if(browser === null){
browser = 0;
}
return browser++;
}
})();
This way the browservariable is not reinitialized on each function call.
UPDATE
You could use a property instead of a variable scoped in a closure for the browser value:
BRB.prototype.getBrowser = function() {
if(!this.browser){
this.browser = 0;
}
return this.browser++;
}

Insert and execute javascript

I have a javascript variable:
var foo='<script type="text/javascript">alert("Hello World");<\/script>'
The variable is inserted with element.innerHTML=foo; after an event occurs on the page, about 10 seconds after the page is loaded.
Is there a way to execute the 'alert' function right after the insertion?
If you absolutely, positively have to take JavaScript code that's in a string and execute it, you basically have to use eval or an eval-like mechanism. In some years of JavaScript programming, I've never had to resort to it, and I do suggest that you look at whether there's another way to achieve your actual overall goal.
So here, you'd strip off the script tag stuff and just eval the code, e.g.:
var script = foo.replace(/^<script[^>]*>/, "").replace(/<\/script>$/, "");
eval(script);
// Or window.evalInGlobalScope(script); // -- See below
Obviously you have to be sure you trust the source of the string, since you're executing the code therein.
eval is a slippery beast and plays very odd games with context and scope. If you need something that looks more like what you'd get if you did add a script tag to the page, here's a function that does that cross-browser (from my answer to this other question here on Stack Overflow):
window.evalInGlobalScope = (function() {
var fname, scr;
// Get a unique function name
do {
fname = "__eval_in_global_test_" + Math.floor(Math.random() * 100000);
}
while (typeof window[fname] !== 'undefined');
// Create test script
scr = "function " + fname + "() { }";
// Return the first function that works:
return test(evalInGlobalScope_execScript) ||
test(evalInGlobalScope_windowEval) ||
test(evalInGlobalScope_theHardWay) ||
evalInGlobalScope_fail;
function test(f) {
try {
f(scr);
if (typeof window[fname] === 'function') {
return f;
}
}
catch (e) {
return false;
}
finally {
try { delete window[fname]; } catch (e) { window[fname] = undefined; }
}
}
function evalInGlobalScope_execScript(str) {
window.execScript(str);
}
function evalInGlobalScope_windowEval(str) {
window.eval(str);
}
function evalInGlobalScope_theHardWay(str) {
var parent, script, d = document;
parent = d.body || d.documentElement || d.getElementsByTagName('head')[0];
if (parent) {
script = d.createElement('script');
script.appendChild(d.createTextNode(str));
parent.appendChild(script);
}
}
function evalInGlobalScope_fail() {
throw "evalInGlobalScope: Unable to determine how to do global eval in this environment";
}
})();
Live example using the above
You don't need to make lots of changes, just one small change.
Right now you have such line of code:
oDiv.innerHTML = foo;
Just change it to those three lines instead:
var oScript = document.createElement("script");
oScript.innerHTML = foo;
oDiv.appendChild(oScript);
And have foo contain only the raw JS, without the <script> and </script> tags.
Live text case.

jJavascript window.onload event correct usage

I have this loop code to reduce the DOM calls in my Javascript, and reuse them.
aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
I have been shown that if the code is ran before the DOM is complete, then the array is null. Moving the script after the last html code will work.
So now I want to put this code inside the window.onload event so to not have to move the script code to the bottom of the page. But it apparently does not work because it appears that the array loop is executed before the DOM is completed.
window.onload=function(){
var aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
}
Also, I have tried to remove the "var" to remove scope without making a difference.
You could also try this approach without using a framework:
window.onload = (function(){
return function(){
var aarr = [];
for (var z=1; z<=10; z++) {
aarr.push(document.getElementById("a"+z));
alert(aarr[z-1].id);
}
};
})();
JSFiddle
If you can use jquery, then you can use the document ready listener:
$(document).ready(function() {
var aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
});
http://www.jquery.com
as per the comment above, have you tried:
if (document.readyState === "complete") { init(); } // call whatever function u want.
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
MDN - window.onload
I guess you try calling code outside of onload. See this fiddle
Better to use a function without pre-scanning the dom to create a cache, Pre-scanning is not needed when you use a simple function with a cache construction. With jQuery you can can create a function like this (native javascript method below this):
window.__jcache = {};
window.$jc = function(u) // jQuery cache
{
if( u == undefined )
{ return window.jQuery; }
if( typeof u == 'object' || typeof u == 'function' )
{ return window.jQuery(u); }
if( window.__jcache[u] == undefined )
{ window.__jcache[u] = window.jQuery(u); }
return window.__jcache[u];
};
Or without a framework (native javascript):
window.__domcache = {};
window.getObj = function(u) // jQuery cache
{
if( u == undefined )
{ return null; }
if( typeof u == 'object' || typeof u == 'function' )
{ return u; }
if( window.__domcache[u] == undefined )
{ window.__domcache[u] = document.getElementById(u); }
return window.__domcache[u];
};
So you can do:
var o = $jc('a1'); // for jquery version
var o = getObj('a1'); // The native javascript method (jamex)
That does the trick.
Greetz, Erwin Haantjes

Listen to state and function invocations

Is it possible to listen to any function invocation or state change
I have a object that wrap another
function wrapper(origiObj){
this.origObj = origObj;
}
var obj = wrapper(document);//this is an example
var obj = wrapper(db);//this is an example
now everytime someone tries to invoke obj.innerHTML or obj.query(..)
I would like to listen to that..
Yes, it's possible:
functions are easy, and properties has to be watched
function FlyingObject(obj){
this.obj = obj;
for(var p in obj){
if(typeof obj[p] == 'function'){
console.log(p);
this[p] = function(){
console.log("orig func");
};
}else{
this.watch(p,function(){
console.log("orig property");
});
}
}
}
var obj = {
f:function(a,b){ return a+b},
m:1
};
var fo = new FlyingObject(obj);
fo.m = 5;
fo.f(1,4);
If your browser/node.js doesn't support Object.watch, check this out:
Object.watch() for all browsers?
Yes you can, define a getter/setter for properties and a shadow function for the function like this: http://jsfiddle.net/fHRyU/1/.
function wrapper(origObj){
var type = origObj.innerHTML ? 'doc' : 'db';
if(type === "doc") {
var orig = origObj.innerHTML;
origObj.__defineGetter__('innerHTML',
function() {
// someone got innerHTML
alert('getting innerHTML');
return orig;
});
origObj.__defineSetter__('innerHTML',
function(a) {
// someone set innerHTML
alert('setting innerHTML');
orig = a;
});
} else if(type === "db") {
var orig = origObj.query;
origObj.query = function() {
//someone called query;
alert('calling query');
orig.apply(this, arguments);
};
}
return origObj;
}
var obj = wrapper(document.body);
obj.innerHTML = 'p';
alert(obj.innerHTML);
var db = function() {}
db.query = function() {alert('foo');}
obj = wrapper(db);
obj.query();
edit: "Deleting" answer since it's tagged node.js, leaving it in case it happens to be useful to anyone else:
The general answer is no, it isn't. At least not in every browser, so any solution anyone gives isn't going to work in many cases.
There are a few things that can work, but again there is horrible support for them:
dom modified events (FF only, I believe)
DOMAttrModified
DOMNodeInserted
DOMNodeRemoved
etc
object.watch (FF only)

Categories

Resources