Scope of my jQuery function? - javascript

I have a file called function.js which has all my jQuery for my aplication which looks like this
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
$('.trigger').click(function(){
$('.stations').find(".drop-down").slideToggle();
return false;
});
...
...
On the top of the file i have my function call insert_initial(); which gets run on the initial load....and this works great..My problem is that i now need to include this js file on my php pages say 1.php and 2.php and 3.php and 1.php is the only one that needs the insert_initial(); ....so i was thinking of the best way to do this. I assumed taking out the function call out of the functions file and putting it into a separate file
<script src="/someting/js/functions.js" type="text/javascript"></script>
<script src="/someting/js/functions_insert.js" type="text/javascript"></script>
and in my functions_insert.js file i would have only
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
});
but that didnt work either...any ideas on how to fix this

This checks to make sure that the location of the current page includes "1.php" before calling insert_initial():
if(window.location.href.indexOf('1.php') != -1)
insert_initial();

I would recommend having your definitions and executions separate in this instance. You don't need to define your functions inside of jQuery's DOM ready event. But it is also good to namespace them as mentioned. A common paradigm I follow is like so:
functions.js
(function($, window, undefined) {
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
window.MyApp = {
update_gallery: update_gallery,
update_prices: update_prices,
insert_initial: insert_initial
};
})(jQuery, window);
1.php
<script src="functions.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
MyApp.insert_initial();
});
</script>
Now you can include your definitions as needed, and call them as necessary.

Try namespacing your functions and attaching them to a nice global object.
window.MyApp = {};
MyApp.insert_initial = function(){
};
Then you can access it from wherever you need, provided it's included earlier in the page.
Edit:
If this doesn't work, you've got an error elsewhere in your code - load order, perhaps? Either method you've described to invoke the function is fine, just make sure it's defined when you invoke it.

Your functions defined in functions.js are only visible in the scope of that document ready function. A simple case where it doesn't work:
(function() {
function square(x) {
return x*x;
}
})();
alert(square(2)); //Fails, since square is not in scope
The easiest way to fix this is to declare your functions in the global namespace:
function square(x) {
return x*x;
};
alert(square(2)); //4

Related

JavaScript Prototypes and jQuery Selectors

I am creating the following code in JavaScript (inside file1.js)
function ABC () {
this.property01 = true;
}
ABC.prototype.doSomething = function () {
if (this.property01 == true) {
// Do something
}
}
Then later in a separate file in my project (lets call it file2.js), I have the following jQuery:
$(document).ready(function() {
var abc = new ABC();
// Some code here
abc.doSomething();
// continue with code
});
So far, everything is correct.
Now, what I would like to do is inside the prototype definition of doSomething() in file1.js, I want to use jQuery. Something along the lines
function ABC () {
this.property01 = true;
}
ABC.prototype.doSomething = function () {
if (this.property01 == true) {
$('#find-element'). .... // ... Do Something
}
}
But I am not sure how to do this. If I wrap the code of file1.js with a jQuery document-ready wrapper, then the line var abc = new ABC(); inside file2.js will throw an error because it no longer recognizes the function definition in file1.js.
Can I use jQuery inside a prototype the way I explained above? How can I do that? How can I structure my files to allow for this to happen?
This should work just fine just as long as jQuery has fully loaded before file1.js and file1.js have. If you explicitly load them in the correct order, the $ will be available globally, and the other files shouldn't have an issue recognizing that object. In fact, if you load things correctly, you shouldn't even need a document-ready setup to gain access to $.
<script src="../jquery.js"></script>
<script src="../file1.js"></script>
<script src="../file2.js"></script>
If, for some reason, you're having conflicts with the $ object, you could also just use the word jQuery to make your calls: jQuery('#find-something')

Calling function/nested function from external js file

I'm having some issues with running some functions from an external js file.
The html includes:
<script src="js/file.js"></script>
<script>
$("#center-button").click(function() {
explodePage("center");
});
</script>
The js file includes:
var explodePage = function(button) {
//code here
aboutPage();
}
var aboutPage = function() {
//code here
}
The explodePage function runs fine, but as soon as it reaches the call to the nested aboutPage function, it starts throwing these uncaught typeerrors at me. It works fine if I don't use an external js file and just put everything into the html. Pretty new to this so probably missing something obvious in scope or something. Any solutions?
Declare the function's definition as below:
function explodePage(button) {
//code here
aboutPage();
}
function aboutPage() {
//code here
}
Explanation:
When you use the var keyword for declaring functions, the execution of JS happens as when the variable is initialized, you cannot reference or use variable's before declaration. In contrast with the name function defintion JS interpreter first picks the enclosed functions before execution and initializes it before the code execution. This is called AST- Abstract syntax tree that is followed by JS interpreters.
Also Remember:
Also bind your Jquery code inside a Jquery document ready function, just to make sure the Jquery and the DOM elements are available for the bindings.
It's not a good a idea to pollute the global window object with variables, since there can be collisions. And immediately-invoked function expression is a good solution for this.
(function(){
//You can declare your functions in here, and invoke them below
$( document ).ready(function() {
//Check that the DOM is ready, in order to manipulate it an add events
$("#center-button").click(function() {
explodePage("center");
});
});
})($); //Notice that we are injecting a dependency, in this case jQuery

Call JQuery function in JavaScript function

I got this JQuery code:
file: code.js
jQuery(function(){
function renderSVG(){
//Something
};
});
File: index.html
<script>
function mostrarOdonto() {
renderSVG();
};
</script>
But i got a problem here:
http://i.gyazo.com/9550a64fc16c7570107706fb2162d84f.png in renderSVG() inside mostrarOdonto()
"Uncaught ReferenceError: renderSvg is not defined"
I tried $renderSVG(); but doesnot work. Anyone can help me?
Thanks so much!
PD: Sorry bad english
That is caused by javascript closures. It is local within the jQuery call and not accessible outside. You can read more about it here: MDN Documentation
You can declare objects outside of the jQuery function call to have it available globally. i.e.:
function RenderSVG(){
//Do Stuff
}
jQuery(function(){
RenderSVG();
});
This ensures that it is accessible outside the jquery scope
or if you really need it within jQuery you can go the route of a jQuery Plugin a la: jQuery docs
Example:
(function( $ ) {
$.fn.renderSVG = function( options ) {
//Do Stuff with canvas since it would be referenced in this.
};
}( jQuery ));
Then you can call it like: $('#mycanvas').renderSVG({/*options*/});
Update 1:
You have to ensure when your code is called after loading jQuery and any plugins.
in your <head> tag
you should put <script src=".../jquery.min.js"> or whatever your file for jquery is called
followed by any plugin scripts ...src="jquery.svg.js", then you put your code:
<script>
function RenderSVG(){
}
//And most important is that you call it after it is ready. In this example
//I use jQuery(window).load you can also use jQuery(document).ready
jQuery(window).load(function(){
RenderSVG();
});
</script>
if it still doesn't work you have to ensure the library for the svg methods aren't doing something weird. To be sure we would have to know the library you are using.
The function renderSVG() is a local function,since it is inside jQuery(function(){ }. It is valid only in that scope , So it is not accessible via other scopes. So try it like this.
<script>
jQuery(function(){
function mostrarOdonto() {
renderSVG();
};
};
</script>
You can Do it in this way JSFIDDLE LINK
HTML:
<input type="button" value="go" onclick=" mostrarOdonto();">
Scripts:
$.renderSVG = function() {
alert("I am calling form jquery");
};
$(document).ready(function() {
alert("function is ready to use now");
});
function mostrarOdonto() {
$.renderSVG();
};
This should work as per your requirement. The Jquery part can go into your Code.js file.
I think could help you it's simple and straight forward
$(document).ready(function() {
mostrarOdonto();
});
function renderSVG() {
alert("Testing purpose only");
};
function mostrarOdonto() {
renderSVG();
};

Loading multiple scripts with same variables/functions

Is it possible to load multiple scripts with same variables/functions in JS, without overriding the old value of the variable. For example to create an own scope/sandbox or object for each loaded script.
Files to load:
script1:
<script>
function init() {
do something...
}
</script>
script2:
<script>
function init() {
do something...
}
</script>
And after loading call script1.init() or script2.init(), is this possible?
You could wrap each section of code with a self invoking anonymous function, which will effectively namespace that section.
(function() {
function init() {
// do something...
}
})();
init(); // ReferenceError
However, if you can't change the code, the second init will overwrite the first definition.
However...
And after loading call script1.init() or script2.init(), is this possible?
...is confusing. Do you already have the init() as methods of an object? If so, they won't overwrite each other.
Unfortunately, no. There is a single global scope on a single page.
However, by using something like the module pattern, you can make a fake namespace:
For example:
var script1 = (function() {
var that = {};
that.init = function() {
do something...
};
more functions...
return that;
})();
And then call it by using script1.init();
You can find out more about the module pattern here.

Is there a way to call a Javascript class method from ExternalInterface?

I can call JS functions with ExternalInterface.call('func_name',.args). OK
But what if I would like to call a js class instance method instead?
ExternalInterface.call('obj.method_name',.args) //this seems not to work
Is there any way of doing it?
It was only a matter of scope. You must instantiated the swf object outside the js class. Then I can reference it in ExternalInterface.call().
window.addEvent('domready',function(){
swf = new Swiff('../files/swf/italy.swf',{
id:'italy',
container:'italy-flash',
width:280,
height:323,
params:{
bgcolor:'#ffffff',
wmode:'opaque',
allowScriptAccess:'always'
}
});
rm = new RelessersManager('regions');
});
Now from the swf I can call the rm methods. :) (.call('rm.method_name',...params))
Previously, I built the swf inside rm, so there was no way to reference rm from the swf.
You can call a JavaScript-Method with ExternalInterface.
Be sure, you have included your JavaScript-Files or you have written your JavaScript-Function inside your index.template.html-file, this could looks like:
<script type="text/javascript" src="./lib/file.js"></script>
<script type="text/javascript">
function doSomtething() {
alert("Something is done");
}
</script>
If you want to call the function "doSomething()" you can do this with the following code:
ExternalInterface.call("doSomething");
If you want to send some parameter and your JavaScript Function is defined like this:
<script type="text/javascript">
function doSomtething(param1, param2) {
alert("Something is done");
}
</script>
You can call it with this statement:
ExternalInterface.call("doSomething", param1, param2);
If this is not working, check your JavaScript-Functions inside your html-file.
You have posted the following statement:
ExternalInterface.call('obj.method_name',.args)
Are you sure you want to send ".args" instead of "args"?
I hope this will help you a little bit.

Categories

Resources