How to write functions in jQuery? - javascript

I'm going to be writing a callable function which will make use of jQuery. But I can't find any reference to ordinary function declaration with jQuery; it's all about element manipulation functions. Can I essentially just declare an ordinary javascript function and then use jQuery in it, or do I need to be doing something special? Is this okay?
function useJQ(xml)
{
var groups = {};
$('resultGroups', $(xml)).each(function() {
var count = $('results', this).length;
var name = $('name',this).text();
groups[name] = count;
}

You need not extend jQuery to do such tasks. You can use plain functions to do what you need to do. just ensure that you don't pollute the global namespace by setting your own namespace.
However, if just want to use the jQuery namespace instead of your own, here's a quick way to add them:
$.fn.functionName = function(){
//do what your function does
//"this" in here is the jQuery object you preceded the function
//to allow chaining, you must return a jQuery object
};
the effect is like:
$(selector).functionName()

jQuery is just a collection of helper functions. It doesn't affect how you define your functions. So your present code will work fine.

jQuery is not about structuring your javascript code, for that you should use Javascript enclosures, objects and prototype. There a many proposed ways of structuring Javascript code.
You could also take a look at defining jQuery plugins authoring to help you keep you code more organized.

Related

Should I put this javascript code in a function?

I'm trying to learn javascript better. There is a lot I don't know, for example, I have this simple code, should it be in a function that calls it's self? Or should I leave it like this? And why?
<script type="text/javascript">
$('.some_ul_class').each(function(i, obj) {
var childrenCount = $(this).find('li').length;
$(this).addClass('li-count-' + childrenCount);
});
</script>
Functions have two purposes in JavaScript:
Controlling scope.
Allowing code to be reusable.
You aren't creating any variables in the global scope, so there is no scope change by using a function.
That leaves allowing code to be reusable. Do you want to call that piece of code multiple times? If so, use a function.
To me this use of jQuery looks ok.
However, I wouldn't choose to use jQuery to add classes in this way.
If the items in your jQuery selector are part of a list, the classes could/should be added by the server in the loop that created them in HTML.
To me the jQuery snippet introduces some magic that can be hard to debug later on.

Wrap a function from a JavaScript library for use in my own JavaScript library

So I am trying to build a JavaScript library. I do not want to write all my functions from scratch, most of the functions I want to use are already available in other libraries, the point of my library is to group these together into my own library to make things easier for continuous use.
I am looking for an example of how to wrap functions from other JavaScript libraries so I can use them within my own.
The way I had thought it would work was I would reference the libraries in which the functions are being taken for at the top of my code
I would then have
function NameOfFunction(){
*wrapped function from referenced library*
}
for each function
You can use oriented-object Javascript, that will allow you to wrap functions from other libraries ; still, be conscious that the external librairies need to be there, or you wouldn't be able to use their functions. ;)
Imagine this kind of code :
var myObject = {};
myObject.myMethod = function( param1, param2 ) {
};
Then you just have to call myObject.myMethod( param, param ), 'cause myObject will be used like an object. We can easily imagine that you wrap libraries functions inside this kind of method, or even simply return a call to another library function.
Does that answer to your question ?
EDIT : and if you really want an oriented-object style, you can do like this
function myObject() {
this.myMethod = function( param1, param2 ) {
return externalLib.myMethod();
}
}
var objInstance = new myObject();
var something = myObject.myMethod();
If your library exposes functions in an object, like underscore or any other utility libraries, then you can use _.extend or jquery extend to copy all of them into a single object.
var myLib = {};
_.extend(myLib,helperLib1,helperLib2,...)

jQuery variable shadowing

There is strange pattern in jQuery:
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
...
return jQuery;
})();
What is the practical reason for this? Why not just expose the inner jQuery function? Is it only for name clashes in the inner jQuery and outer jQuery since both are in closures.
jQuery.noConflict(true) removes the global name for jQuery. However, it would be impossible to program the rest of the jQuery library without using some name for the object, so a local, non-exposed name needs to be used. For convenience, they redefine jQuery as a variable in the scope of the anonymous function.
The pattern itself is called module pattern. It´s not specific for jQuery and it´s not strange but very helpful. It allows for hiding of the objects state and implementation. It also allows for priveleged methods (public methods with access to private data) and other good design principles.

What javascript coding style is this?

I am working on maintaining a ASP.NET MVC application that has the following coding style. The view has:
<script type="text/javascript">
$(document).ready(function() {
SAVECUSTOMERS.init();
});
</script>
There is a js file included that goes along these lines:
var SAVECUSTOMERS = (function() {
init = function () {
$("#saveCust").bind("click", OnSave);
$("#cancel").bind("click", OnCancel);
},
OnSave= function() {
//Save Logic;
},
OnCancel = function() {
//Cancel logic;
}
return { init: init };
})();
Is this a best practices JS coding style? Is the intent to have non obtrusive JS?
What is the SAVECUSTOMERS? I understand that there are different ways of creating classes in javascript (per this link), but this style does not fall into any of those categories listed
Where can I find more information on this style of JS coding?
1) Using a $(document).ready (or similar function from another library) function is considered standard practice in JavaScript. First of all, it ensures your JavaScript executes on page that has finished evaluating/building it's DOM. And it also abstracts away some of the browser-implementation inconsistencies when identifying when the DOM is in fact ready. But I assume you are mainly referring to the 2nd code block.
What you see there is that SAVECUSTOMERS is assigned the result of a self-executing an anonymous function. This is done for a few reasons, the most common being the ability to control the scope and 'namespace' of the functions and data inside the anonymous function. This is because JavaScript has lexical scope, and not block level scope.
The practice of using these self-invoking functions in JavaScript is very common
However the code itself has several problems. The variables init, OnSave and OnCancel are declared as global variables (because the var keyword was omitted). This largely defeats the purpose of wrapping them in an self-invoking function. Furthermore, the contents of that function are using a mix of object assignment syntax and standard expression syntax, which will result in syntax errors.
Also, by returning only the init function, the onSave and onCancel functions have been effectively 'hidden' or made 'private' through the use of closures. This helps keep namespaces clean and encapsulated.
If I were writing this code (some personal perferences here, there are a few ways to accomplish something simliar), then it would look like this:
var SaveCustomers = (function($) {
var init = function () {
$("#saveCust").bind("click", onSave);
$("#cancel").bind("click", onCancel);
};
var onSave = function() {
//Save Logic;
};
var onCancel = function() {
//Cancel logic;
}
return { init: init };
})(jQuery);
Some notes on the above:
I declare variables using the var keyword. This keeps their scope local to this function (you could also technically use named functions declarations as well)
I pass jQuery as the parameter in the self-invoking function, and assign it to $ as the argument in the function call. This protects the $ variable inside the function so that we know it references jQuery, and hasn't been munged by a secondary library that also uses $.
2) SAVECUSTOMERS is a basic JavaScript object, which has a single owned property called 'init', whose value is a function, as defined by the init declaration inside the execution.
3) Not sure about how to answer this question - your best bet for understanding JavaScript best practices is to read through other JavaScript code that is known to be of quality, such as the jQuery source, or Prototype, or Underscore, etc.
this style is known as jquery ... have you checked the JQuery website, go through it ...
This is called self-invoking functions in javascript. One of the articles I am giving below. you can get more on google.
http://2007-2010.lovemikeg.com/2008/08/17/a-week-in-javascript-patterns-self-invocation/
If you are referring to the $ programming, then its related to JQuery which other answers have provided links too.
It's using the JQuery library.
JQuery includes a function called $(), which allows you to select elements from the DOM using a CSS-like syntax.
The $(document).ready bit is a standard JQuery method for making sure that the enclosed code only gets run after the page has finished loading. This is required to ensure that events get correctly attached to the relevant DOM objects.
The bit with functions being used as arguments for others functions is known as a 'closure' it's a very common way of writing Javascript, but in particular when using JQuery, which goes out of its way to make things easy to do and minimal code with this coding style.
See this page: http://blog.morrisjohns.com/javascript_closures_for_dummies for a beginners discussion of how closures work in Javascript and how to write them (note that this page doesn't look at JQuery at all; closures are a Javascript feature that is used heavily by JQuery, but you don't need JQuery to write closures)
This is a normal way to use jQuery for handling events.
What basicly happens is that you check that the document is loaded hence
$(document).ready(function() {
SAVECUSTOMERS.init();
});
And when it is you start to add your bindings to buttons or what ever they might be.
The intent of the code in SAVECUSOMTERS is to mimic private and public properties in objects. Since JS does not support these by default, this self invoking function executes and returns a certain number of properties. In this case it returns the 'init' method. Despite the fact that you see OnSave and OnClick, you'll find that you can't access them at all. They are "private" and only used internally within that function.
The $() function is part of a javascript library called jQuery http://jquery.com It's a pretty well rounded library and primarily is used for DOM manipulation.
The $(document).ready() function is a way for jQuery to continuously poll the page until it is loaded. When it is, the javascript within is executed.
The goal is to have public and private functions. OnSave and OnCancel are private functions that are only accessible within the scope of the self-executing anonymous (function() { ... } ()) which returns an object that gives access to the init function publicly.
SAVECUSTOMERS becomes the object returned by the above mentioned function, i.e. { init: init }, an object with one method init that has access to the functions within that closure.
You can read Douglas Crockford's Javascript: The Good Parts or Stoyan Stefanov's Javascript Patterns
Other notes:
The $() functions belong to the jQuery library
There are syntax errors because the functions should be separated by ; not , since they are within a function, not an object.

jQuery: Global Variable Namespace Problem

Is there a way to declare a global variable in jQuery in its own namespace?
Sure, I can declare global variables with plain old JavaScript, but they will fall in the window's namespace. For example, if I had a variable named document, it would surely overwrite the document object of the window.
Does jQuery have a hash table that lets you store any object by their name?
Thanks.
Not sure why you want to use jQuery for that? You could just create your own namespace:
var namespace = {
document : "Foo"
};
Please elaborate, if there's some need to use jQuery somehow.
Of course you can. Create a namespace as an object and then attach it to the jQuery function.
(function ($) {
$.myNamespace = {};
})(jQuery);
Here I've created an auto-executing anonymous function to do the work. I can then add other propertes and functions to the namespace inside this function. Also this avoids the problem of someone else renaming $ to something else.
After this is done you can refer to your namespace as jQuery.myNamespace
If the variable is something that want to associate with an element to be used later, maybe in a different routine, you could use jQuery's "data" method to store it.
e.g.
:
:
// Save original HTML content.
var old_html = $('#box').html();
$('#box').data({originalContent: old_html});
// Replace with new content.
$('#box').empty().html(new_html);
:
// Restore original content (maybe in a different function).
var orig_html = $('#box').data('originalContent');
$('#box').empty().html(orig_html);
:
I hope this is useful to you.
Regards
Neil

Categories

Resources