Skip to content

Instantly share code, notes, and snippets.

@crisu83
Last active December 11, 2015 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crisu83/4678224 to your computer and use it in GitHub Desktop.
Save crisu83/4678224 to your computer and use it in GitHub Desktop.
A function for registering JavaScript events based on an array ($name => $handler).
<?php
/**
* Registers a specific Bootstrap plugin with the given selector and options.
* @param string $name the plugin name.
* @param string $selector the CSS selector.
* @param array $options plugin JavaScript options.
* @param int $position the position of the JavaScript code.
*/
public function registerPlugin($name, $selector, $options = array(), $position = CClientScript::POS_END)
{
if (isset($options['events']))
{
$this->registerEvents($selector, $options['events'], $position);
unset($options['events']);
}
$options = !empty($options) ? CJavaScript::encode($options) : '';
Yii::app()->clientScript->registerScript(
$this->generateRandomId(), "jQuery('{$selector}').{$name}({$options});", $position);
}
public function registerEvents($selector, $events, $position = CClientScript::POS_END)
{
$script = '';
foreach ($events as $name => $handler)
{
$handler = new CJavaScriptExpression($handler);
$script .= "jQuery('{$selector}).on('{$name}', {$handler});'";
}
// Generate a "somewhat" unique id for the script snippet.
$id = __CLASS__ . '#' . sha1($selector . serialize($events));
Yii::app()->clientScript->registerScript($id, $script, $position);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment