Last active
December 11, 2015 23:39
-
-
Save crisu83/4678224 to your computer and use it in GitHub Desktop.
A function for registering JavaScript events based on an array ($name => $handler).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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