0

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;
}
4
  • 3
    Yep, you can use jQuery in any standard Javascript. Keep in mind that jQuery is just a Javascript library itself, it's not magic :) Commented Apr 29, 2012 at 5:35
  • 1
    use a closure. (function($){ ...code... })(jQuery) anything inside the function that uses $ is binded to jquery. Commented Apr 29, 2012 at 5:35
  • Feels like magic...very complex and powerful magic which I need to read up on before casting any spells with. Commented Apr 29, 2012 at 5:36
  • And although I think I won't need it, I'd like to understand: what do you mean "bound to jQuery", and why would I want to as opposed to just going it straight? Commented Apr 29, 2012 at 5:37

3 Answers 3

4

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.