Making Functions Public from Inside jQuery Function - javascript

I have a block of JavaScript/jQuery that works fine.
<script type="text/javascript">
$(function () {
function doSomething() {
// Do something amazing here!
}
// Many various jQuery handlers and support functions
});
</script>
But now I'd like my doSomething() function to be callable from another block of script on the same page.
I understand I can do that by moving doSomething() outside of the jQuery function ($(function () {})). But then doSomething() wouldn't be able to call the helper functions inside of the jQuery function.
I could move the other functions outside of the jQuery function, but some of them are handlers that need to be initialized, and they share they same helper functions.
Is there a way to keep all my functions inside my jQuery function, but just make one of them visible outside of it?
And any suggestions on where I could go to read up on this?

JavaScript has functional scope. So, the reason you can't call your function if it is nested within
$(function () { ... });
is because it is only accessible within that function's scope.
You can easily move that function definition:
function doSomething() { ... }
outside of the $(function(){...}) function and still have access to variables within the $(function(){...}) function's scope by passing the variables as parameters to the function and then having it return any modifications:
$(function () {
var blah = 'blah';
var result;
result = doSomething(blah);
// Many various jQuery handlers and support functions
});
function doSomething(blah) {
// Do something amazing here!
return newBlah;
}
// Now you can call your doSomething function in the global scope too
var example = "test";
var result = doSomething(example);

Well, in fact you should move your logic from this wrapper.
It's intended for initialization of logic that should run after DOM is ready. You shouldn't make any functions here.
Consider following pattern for your code:
(function($) {
// Your logic here
// You could safely export your functions to
// global scope from here, if you really need
var app;
app = {
forms: doSomething
};
function doSomething() {
// Do something amazing here!
}
window.app = app;
$(function() {/* start interact with DOM */});
}(jQuery));

You can do it extending jQuery:
$.extend({
foo: new function () {
var _self = this;
_self.doSomething = function () {
};
_self.initialize = function () {
$('#button-x').click(function(){
_self.doSomething(); //use the function inside
});
};
});
$(function () {
$.foo.initialize();
$.foo.doSomething(); //use the function outside
});

Related

How to call function inside function through only HTML

I just can't reach the function inside function using only HTML.
How to call setLayout() using only HTML or is it able to call only in Javascript?
<button onclick="customize.setLayout('b.html');">Click Please</button>
Javascript:
function customize() {
function setLayout(text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
}
}
It isn't possible to call setLayout at all.
Functions defined in other functions are scoped to that function. They can only be called by other code from within that scope.
If you want to to be able to call customize.setLayout then you must first create customize (which can be a function, but doesn't need to be) then you need to make setLayout a property of that object.
customize.setLayout = function setLayout(text) { /* yada yada */ };
Multiple ways to call a function within a function. First of all, the inner function isn't visible to the outside until you explicitly expose it Just one way would be:
function outerobj() {
this.innerfunc = function () { alert("hello world"); }
}
This defines an object but currently has no instance. You need to create one first:
var o = new outerobj();
o.innerfunc();
Another approach:
var outerobj = {
innerfunc : function () { alert("hello world"); }
};
This would define an object outerobj which can be used immediately:
outerobj.innerfunc();
if you insist to do it this way, maybe define setLayout and then call it,
something like this:
<script>
function customize(text, CallSetLayout) {
if (CallSetLayout) {
(function setLayout(text) {
//do something
alert(text);
})(text);
}
}
</script>
<button onclick="customize('sometext',true);">Click Please</button>
then you can decide if you even want to define and call setLayout from outside
Simple answer: You can't call setLayout() with this setup anywhere!
The reason being, setLayout() will not be visible outside of customize() not even from other JavaScript code because it is defined locally inside customize() so it has local scope which is only available inside customize(). Like others have mentioned there are other ways possible... (^__^)
You can return the response of setLayout() by returning it as a method of customize() and use it in your HTML like customize().setLayout('b.html'); e.g.
<button onclick="customize().setLayout('b.html');">Click Please</button>
JavaScript:
function customize() {
var setLayout = function (text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
};
return {
setLayout: setLayout
};
}
Another Approach
You can also define your main function i.e. customize as Immediately-Invoked Function Expression (IIFE). This way you can omit the parenthesis while calling its method in HTML section.
<button onclick="customize.setLayout('b.html');">Click Please</button>
JavaScript
var customize = (function () {
var setLayout = function (text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
};
return {
setLayout: setLayout
};
})();
You need to treat it as object and method
<button onclick="customize().setLayout('b.html');">Click Please</button>
Sorry I had to edit this code for more clarification
function customize() {
this.setLayout = function setLayout(text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
}
return this;
}

Using onclick() inside another function

function layoutMod() {
standardId = document.getElementById("standard");
fancyId = document.getElementById("fancy");
standardId.onclick = function() {
standard();
};
fancyId.onclick = function() {
fancy();
};
};
How can I use the onclick events defined above in a function??? Is it a good practice to load the function at page load?? I need to define in a function the onclick event beacuse I don't want to use global variables.
What you've written should work. However, you should note that by not using the var keyword, you're still creating global variables inside of your function. I would suggest...
function onloadHandler() {
document.getElementById("standard").onclick = function() {
// Do something
};
document.getElementById("fancy").onclick = function() {
// Do something else
};
};
It can get messing when you nest functions inside of each other. In this case, I would suggest removing the outer function so that your code looks like this:
document.getElementById("standard").onclick = function() {
standard();
};
document.getElementById("fancy").onclick = function() {
fancy();
};
The code does not need to be in a function, it will automatically be run on page load. Since you don't want global variables, just don't use variables at all.

jQuery: When getting the value of an element, do I need to declare the variable in document ready?

I'm storing the value of a specific form element as a variable. This same value is used in multiple functions.
function one() {
var selectedRole = $('#RegistrationRole_ID').val();
}
function two() {
var selectedRole = $('#RegistrationRole_ID').val();
}
I'd like to make this a global variable so I don't have to keep selecting it in each of my functions. So my question is, am I able to still get the value correctly if I declare the variable outside of my document ready block?
<select id="RegistrationRole_ID">
<option value="1">one</option>
</select>
I think I might have answered my own question...it's possible that the value may change from when the document is loaded. Really, what I am trying to do is remove duplicate code, where I get the value of the element multiple times. Do you have a suggestion for this?
I would suggest not doing that. If you want quicker/easier access, write a function:
var getRoleId = (function() {
var roleField = $('#RegistrationRole_ID').get(0);
return function() {
return roleField.value;
};
})();
Now you can write
if (getRoldId() == 22) { // whatever }
The advantage is that you're really not repeating yourself: that role field, with it's global unique "id" value, is already (in essence) a "global variable". The function just makes sure you're not performing redundant "document.getElementById()" calls (via jQuery), but it keeps thing honest and avoids potential problems of the script "cached" value getting out-of-sync.
Yes. But use var only once, since it declares the variable.
var selectedRole; // selectedRole is now global.
function one() {
// If one() is called after doc ready
// selectedRole will be $('#RegistrationRole_ID').val();
// in it.
}
function two() {
// If two() is called after doc ready
// selectedRole will be $('#RegistrationRole_ID').val();
// in it.
}
$(function() {
selectedRole = $('#RegistrationRole_ID').val(); // This change that global
// Now you can use one() and two() w/o redoing the same jQuery
// over and over again.
one(); two();
});
A better option. Just use a big enough scope for all your variables / functions with a self executing anonymous function:
(function() {
var selectedRole; // selectRole is now available everywhere in the anon fun()
// but it is not global
function one() {
...
}
function two() {
...
}
$(function() {
selectedRole = $('#RegistrationRole_ID').val(); // Change the variable
// Now you can use one() and two() and
// selectedRole will be available:
one(); two()
});
}());

Is this how you define a function in jQuery?

Is this how you define a function in jQuery?
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
});
Now to call the function I do:
MyBlah('hello');
First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.
Here's an example:
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
MyBlah("Hello this works") // Inside the anonymous function we are cool.
});
MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)
This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.
Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.
Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).
Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:
$('div#message').myBlah("hello")
See also: http://www.re-cycledair.com/creating-jquery-plugins
No, you can just write the function as:
$(document).ready(function() {
MyBlah("hello");
});
function MyBlah(blah) {
alert(blah);
}
This calls the function MyBlah on content ready.
No.
You define the functions exactly the same way you would in regular javascript.
//document ready
$(function(){
myBlah();
})
var myBlah = function(blah){
alert(blah);
}
Also: There is no need for the $
You can extend jQuery prototype and use your function as a jQuery method.
(function($)
{
$.fn.MyBlah = function(blah)
{
$(this).addClass(blah);
console.log('blah class added');
};
})(jQuery);
jQuery(document).ready(function($)
{
$('#blahElementId').MyBlah('newClass');
});
More info on extending jQuery prototype here: http://api.jquery.com/jquery.fn.extend/
jQuery.fn.extend({
zigzag: function () {
var text = $(this).text();
var zigzagText = '';
var toggle = true; //lower/uppper toggle
$.each(text, function(i, nome) {
zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
toggle = (toggle) ? false : true;
});
return zigzagText;
}
});
The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.
$(document).ready(function(){
$.myFunction = function(){
alert('You have successfully defined the function!');
}
$(".btn").click(function(){
$.myFunction();
});
});
You can see an example here: How to define a function in jQuery?
That is how you define an anonymous function that gets called when the document is ready.

Best practices for declaring functions inside jquery ready function

I haven't found a good reference for declaring my own functions inside the
jquery.ready(function(){});
I want to declare them so they are inside the same scope of the ready closure. I don't want to clutter the global js namespace so I don't want them declared outside of the ready closure because they will be specific to just the code inside.
So how does one declare such a function...and I'm not referring to a custom jquery extension method/function...just a regular 'ol function that does something trivial say like:
function multiple( a, b ){
return a * b;
}
I want to follow the jquery recommendation and function declaration syntax. I can get it to work by just declaring a function like the multiply one above...but it doesn't look correct to me for some reason so I guess I just need some guidance.
I believe that you would be okay just declaring the function inside the ready() closure, but here you can be a bit more explicit about the local scoping:
jQuery.ready(function() {
var myFunc = function() {
// do some stuff here
};
myFunc();
});
It might sound simple but you just ... declare the function. Javascript allows functions to have inner functions.
$(document).ready( function() {
alert("hello! document is ready!");
function multiply(a, b) {
return a * b;
}
alert("3 times 5 is " + multiply(3, 5));
});
I have a StartUp function, and I use it as printed bellow:
function StartUp(runnable)
{
$(document).ready(runnable.run);
}
var ExternalLinks =
{
run: function()
{
$('a[rel="external"]').bind('click', ExternalLinks.click);
},
click: function(event)
{
open(this.href);
return false;
}
}
StartUp(ExternalLinks);
var ConfirmLinks =
{
run: function()
{
$('a.confirm').bind('click', ConfirmLinks.click);
},
click: function(event)
{
if (!confirm(this.title)) {
return false;
}
}
}
StartUp(ConfirmLinks);
My web sites are modular, so every module has N actions and every action can have a .js file, so I just write function and call it with StartUp(...functionName...)

Categories