This site is built with Viewi itself. It is experimental and still in development. If you see any bugs please do not hesitate and open an issue or DM me on Twitter.

Javascript Components

Writing your components in PHP is pretty good. But what if you need to write some javascript code for your own. For that there is a mechanism of inserting the javascript parts into your PHP components by using the HEREDOC strings:

// console log component’s property: name
// To access the component in your javascript code use $this. 
// All local variables are also available. 
// Names are being converted though, to have more javascript look:
// without $ prefix. Exception is $this itself.
$localVar = 'my local variable';
<<<'javascript'
console.log($this.name);
console.log(localVar);
javascript;
// to have an interpolation available
<<<javascript
$somePhpVariable
<<<javascript;

More useful example:

class GoogleSignInButton extends BaseComponent
{
    // ...
    public function __rendered()
    {
        <<<'javascript'
        gapi.signin2.render('google-signin', {
            'scope': 'profile email',
            'width': 240,
            'height': 40,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': $this.loginGoogle,
            'onfailure': $this.loginGoogle
        });
        javascript;
    }
    // ...
}

But what if you want to write the entire component or service in pure javascript? Simply because it is more comfortable writing complex UI behavior, which is expected on frontend only. For that you can create another one file in addition to your php file, like this:

  • Slider.php
  • Slider.js
  • Slider.min.js (optional, you can create a minified version as well if you want)

Now let’s write our PHP and javascript versions of a service:

Slider.php
class Slider
{
    public function setup(string $selector, array $options)
    {
	// nothing on backend
    }
}

Slider.js
var Slider = function () {
    this.setup = function (selector, options) {
        // execute some javascript to make slider work
    };
};