Skip to content
This repository was archived by the owner on Jul 19, 2019. It is now read-only.

Allow component scope to be set #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions ReactJS.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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);

Expand Down Expand Up @@ -137,15 +169,16 @@ 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
);
}

/**
* 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
Expand All @@ -167,5 +200,4 @@ private function executeJS($js) {
}
}
}

}