Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
54
Добавлен:
14.03.2016
Размер:
12.64 Mб
Скачать

CHAPTER 18 USING JQUERY

else {

// User is eligible to vote.

$output .= l(t('Vote'), "plusone/vote/$nid", array( 'attributes' => array('class' => 'plusone-link') ));

}

$output .= '</div>'; // Close div with class "vote".

$output .= '</div>'; // Close div with class "plusone-widget".

print $output;

In the preceding code, we used the variables set in the hook_node_load in the plusone- widget.tpl.php—enabling us to display the widget. Creating a separate theme template rather than building the HTML inside the module itself allows designers to override this function if they want to change the markup.

The HTML of the widget that would appear on the page http://example.com/?q=node/4 would look like this:

<div class="plusone-widget"> <div class="score">0</div> <div class="vote">

<a class="plusone-link" href="/plusone/vote/4">Vote</a> </div>

</div>

Using Drupal.behaviors

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'

});

414

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]