3

I have a custom views plugin. When the view is displayed, the javascript below gets loaded. Note the custom method, do_stuff, which gets called from within Drupal.behaviors.

(function ($) {
  $.fn.do_stuff(indx){
    alert (indx);
  }
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      if (settings.hasOwnProperty('mymodule')) {
        $('.my-item').each(function(indx, item) {
          // do stuff to each item
          $(this).do_stuff(indx);
        });
      }
    }
  } 
}(jQuery));

I would now like to create a second plugin, which loads a second javascript file. This second javascript file needs access to the custom method, do_stuff. Is there a way I could access the do_stuff code defined in the first javascript file, from within the second javascript file? For example, is there a way to move the custom method inside Drupal.behaviors, so that it could then be accessed from within any other javascript file?

1 Answer 1

3

I use a slightly different JS pattern with Drupal, which is based on the Javascript Module Pattern.

var FOO = (function(me, $, Drupal, undefined) {
  me.name = "FOO";

  function do_something_awesome () {
  }

  me.do_stuff = function do_stuff () {
  }

  function init (context, settings) {
    me.do_stuff();
    do_something_awesome();
  };

  Drupal.behaviors[me.name] = {
    attach: init
  };

  return me;
}(FOO || {}, jQuery, Drupal));

Anything directly attached to me will be public on the FOO. The rest is private. Typically, I will pass in FOO into the closure in dependent libraries.

2

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.