Drupal provide a mean to pass information easily to JavaScript. Many applications want to pass configuration information to JavaScript that runs on a page.
"Hello World!"), 'setting');
//Inline Js
drupal_add_js('alert(Drupal.settings.helloworld);', array('type' => 'inline', 'scope'=> 'footer'));
?>
Sometime it happens that you might have changed the class or id of the element after the page have fully loaded in this scenario javascript won't be able to detect the newly added classes (though there are other way to do it with jQuery). But in drupal, behaviors will help you out to handle this situation.
Here are some examples where drupal behaviors come handy:
CTools calls it after a modal has been loaded.
Media calls it after the media browser has been loaded.
Panels calls it after in-place editing has been completed.
Views calls it after loading a new page that uses AJAX.
Views Load More calls it after loading the next chunk of items and
JavaScript from custom modules may call Drupal.attachBehaviors() when they add or change parts of the page.
Drupals official JavaScript documentation suggests that modules should implement JavaScript by attaching logic to Drupal.behaviors
example:
Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
$('.locatoinCL', context).click(function () {
$(this).toggle('show');
});
}
};
// Attach all behaviors.
$(function () {
Drupal.attachBehaviors(document, Drupal.settings);
});
where $(function () is a shorthand for $(document).ready() and context is a dom and class locatoinCL is added after the page is loaded
Drupal core will call attached behaviors when the HTML is fully loaded, and passing in two arguments
- context : contains the DOM.
- settings : contains all the settings injected from server side.
0 Comment(s)