User login

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

Searched words: 
define and use function in jquery abstract javascript code

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.