Define and Use a JQuery Plugin as a Helper Function for Drupal JavaScript
Here's the basics of defining and using a JQuery plugin within the context of Drupal.
This is definitely not the best and highest use of a plugin, and may in fact be a downright abomination-- this isn't a plugin that really works outside the context of the code it is written for, and certainly not outside Drupal. But it was a clean way to abstract out 42 lines of code, so here it is, for the enjoyment of all.
The first part here is simply how to call JQuery from Drupal, the second part is the plugin.
(function ($) {
Drupal.behaviors.pendingUser = {
attach: function(context, settings) {
context = context || document;
settings = settings || Drupal.settings;
/* Some code here */
$('#pendinguser-approve').pendinguserProcess();
};
}) (jQuery)
$.fn.pendinguserProcess = function(context, settings) {
/* We need to grab our Drupal context and settings if we want to use them. */
context = context || document;
settings = settings || Drupal.settings;
/* See http://addictedtonew.com/archives/414/creating-a-jquery-plugin-from-scratch/ */
return this.each(function() {
$(this).click( function(a) {
/* Lots more code. */
/* A function defined within the scope of our plugin. */
pendinguserButtonsToggle(false);
});
});
function pendinguserButtonsToggle(add) {
$('#pendinguser-approve, #pendinguser-reject').toggleClass('disabled', add);
}
};
})(jQuery);
And see the current version of this code in the pendinguser module's repository, right here:
http://drupalcode.org/project/pendinguser.git/blob/refs/heads/7.x-1.x:/pendinguser.js
Comments
Post new comment