How can I create a jQuery function like
$.MyFunction(/*optional parameter*/)?
which will return a bool?
note:
I’ve tried this:
jQuery.fn.isValidRequest = function (options) {
return true;
}
// I'm contending with Prototype, so I have to use this
jQuery(document).ready(function ($) {
// and jQuery 1.2.6, supplied by the client - long story
$('a').livequery('click', function () {
alert($.isValidRequest("blah"));
return false;
});
});
but it crashes on the alert() with
Microsoft JScript runtime error: Object doesn't support this property or method
This is what worked in the end:
jQuery.isValidRequest = function (options) {
return true;
}
For a function you intend to call from jQuery instances, you’d define it like this:
And call like any other jQuery method:
A function intended to be called from the global jQuery object (or its $ alias) would be attached directly to that object:
And call the same way:
Note that I’ve used $.fn for brevity – this can cause problems if jQuery is prevented from using the $ alias for compatibility with other libraries. The recommended way to attach a plugin function is:
Note also that most jQuery functions return
this, to enable chaining; if you opt to return some other value, you’ll be unable to do this. Be sure to document clearly that your function returns a boolean, or you’ll find yourself wondering why e.g.$("...").MyFunction().hide()breaks later on.You can read more about extending jQuery here:
Extending jQuery – plugin development
and in the jQuery documentation:
Plugins/Authoring