3

I need to add my own little if's and checks in 3 functions inside

misc/ajax.js (
  Drupal.ajax.prototype.beforeSend,
  Drupal.ajax.prototype.success,
  Drupal.ajax.prototype.error
)

How can I override them in my module? I can't find a manual and it's not in Examples for Developers. Sorry if it seems a dumb question, but I'm a php developer - I can work with js, but I'm not so fluent with it.

  • Can I simply write it in my module's js file?
  • If 2 or 3 modules needs to modify them, how to avoid conflicts?

2 Answers 2

3

Drupal.ajax.prototype.beforeSend and the others are just variables that happen to have functions assigned to them. As long as your code appears in the page build after the original function implementations, you you should be able to just override what's already there:

(function($) {
  // In mymodule.js, which appears after ajax.js in the page build
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    // Replacement code.
  }
})(jQuery);
4
  • So, I'm doing it the right way, but that leaves my doubt - each module must take care to be the last one updating them on the page that needs it's changes, right? No way to prevent accidental modifications by others?
    – Mołot
    May 14, 2013 at 14:09
  • 4
    Correct, this practice is usually referred to as 'monkey patching' and it's not an exact science unfortunately
    – Clive
    May 14, 2013 at 14:10
  • Oh. I was so sure there is some clean, safe, clever way I just cannot find due to my lack of js skill... I wouldn't asked if I knew. But I think I'll leave this question for future users looking for that nonexistent safe way.
    – Mołot
    May 14, 2013 at 14:12
  • Using other frameworks (Require.js, AngularJS, anything else that tries to bring Dependency Injection to Javascript) there are more satisfying ways of achieving the same results, but with plain 'ol JS/jQuery not so much. Your method is the best that I know of on top of Drupal
    – Clive
    May 14, 2013 at 14:16
7

This might be a better way:

(function ($) {
  // Drupal's core beforeSend function
  var beforeSend = Drupal.ajax.prototype.beforeSend;
  // Add a trigger when beforeSend fires.
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    beforeSend.call(this, xmlhttprequest, options);
    $(document).trigger('beforeSend');
  }
})(jQuery);

https://www.drupal.org/node/1372840

Your Answer

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

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