From e9b0d39869ac31c31c7ff89806d678c517cf18cf Mon Sep 17 00:00:00 2001 From: Jon Alport Date: Fri, 26 Feb 2016 17:04:10 +1100 Subject: [PATCH] Allow component scope to be set --- ReactJS.php | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/ReactJS.php b/ReactJS.php index 8877e37..6bacd21 100644 --- a/ReactJS.php +++ b/ReactJS.php @@ -22,6 +22,12 @@ class ReactJS { */ $component, + /** + * The JavaScript scope in which React components are contained (defaults to null) + * @var string + */ + $componentScope = null, + /** * Properties that go along with the component * @var mixed @@ -81,6 +87,31 @@ function setComponent($component, $data = null) { return $this; } + /** + * Sets the JavaScript scope in which React components are contained + * + * @param string $scope The JavaScript scope (Eg. 'window.app.components') + * @return ReactJS $this instance + */ + function setComponentScope($scope) { + $this->componentScope = $scope; + return $this; + } + + /** + * Returns the component scope, including "dot" delimiter + * + * @return string HTML string + */ + function getComponentScope() { + if ($this->componentScope != null) { + return $this->componentScope . '.'; + } + else { + return ''; + } + } + /** * Custom error handler. The default one var_dumps the exception * and die()s. @@ -100,7 +131,8 @@ function setErrorHandler($err) { */ function getMarkup() { $js = sprintf( - "print(ReactDOMServer.renderToString(React.createElement(%s, %s)))", + "print(ReactDOMServer.renderToString(React.createElement(%s%s, %s)))", + $this->getComponentScope(), $this->component, $this->data); @@ -137,7 +169,8 @@ function getJS($where, $return_var = null) { return ($return_var ? "var $return_var = " : "") . sprintf( - "ReactDOM.render(React.createElement(%s, %s), %s);", + "ReactDOM.render(React.createElement(%s%s, %s), %s);", + $this->getComponentScope(), $this->component, $this->data, $where @@ -145,7 +178,7 @@ function getJS($where, $return_var = null) { } /** - * Executes Javascript using V8JS, with primitive exception handling + * Executes JavaScript using V8JS, with primitive exception handling * * @param string $js JS code to be executed * @return string The execution response @@ -167,5 +200,4 @@ private function executeJS($js) { } } } - }