Using Drupal.behaviors

We encourage users to post events happening in the community to the community events group on https://www.drupal.org.
RavindraSingh's picture

JavaScript interaction works by attaching behaviors (i.e., actions triggered by events such as a mouse click) to elements in the DOM. A change in the DOM can result in this binding being lost. So while the plusone.js file we used previously will work fine for a basic Drupal site, it might have trouble if other JavaScript files manipulate the DOM. Drupal provides a central object called Drupal.behaviors with which JavaScript functions may register to ensure that rebinding of behaviors takes place when necessary. The following version of plusone.js allows voting via AJAX just like the previous version but safeguards our bindings by registering with Drupal.behaviors:

Drupal.behaviors.plusone = function (context) {
jQuery('a.plusone-link:not(.plusone-processed)', context)
.click(function () {
var voteSaved = function (data) {
jQuery('div.score').html(data.total_votes);
jQuery('div.vote').html(data.voted);
}
jQuery.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
success: voteSaved,
data: 'js=1'
});