Výhody použití Behaviors v Drupalu:
Příklad obecného jQuery:
$(document).ready(function () {
// Do some fancy stuff.
});Příklady použítí jQuery v Drupal 7:
A)
(function ($) {
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.my_custom_behavior = {
attach: function(context, settings) {
// Place your code here.
}
};
})(jQuery);B)
// JavaScript should be made compatible with libraries other than jQuery by // wrapping it with an "anonymous closure". See: // – https://drupal.org/node/1446420 // – http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth (function($, Drupal, window, document, undefined) { Drupal.behaviors.myModuleBehavior = { attach: function (context, settings) { $('input.myCustomBehavior', context).once('myCustomBehavior', function () { // Apply the myCustomBehaviour effect to the elements only once. }); } }; })(jQuery, Drupal, this, this.document);
Příklad předání proměnné z PHP do JavaSkriptu:
drupal_add_js(array('myTyxModule' => array('tax_rate' => '0.021')), 'setting');(function($) {
Drupal.behaviors.myTyxModule = {
attach: function (context, settings) {
// You can access the variable by using Drupal.settings.myTyxModule.tax_rate
alert(Drupal.settings.myTyxModule.tax_rate);
}
};
})(jQuery);Dokumentace: