Faloude Faloude - 1 month ago 17
PHP Question

SilverStripe using requirements() for each AJAX call

I'm using a JS script for UI purposes in the CMS area by using a decorator for

LeftAndMain
.

class LeftAndMainTweaks extends LeftAndMainExtension {
public function init() {

parent::init();

// My JS script
Requirements::javascript('mymodule/js/myscript.js');
}
}


The script is loaded only once and not again for each AJAX call (like browsing through pages or ModelAdmin's) which breaks some of the JS functionalities.

How do you force the an external JS script to be reloaded after each AJAX call?

Answer

You should not have to force reloading of scripts. Use entwine hooks instead.

A common pattern is to use onmatch and onunmatch, eg.

$('.my-selector').entwine({
    onmatch: function () {
        // don't forget to call this._super();
        this._super();

        // Do your stuff to initialize your component
    },

    onunmatch: function () {
        this._super();
        // clean up your component, unbind event listeners etc.
    }
});

If a view creates a node with the .my-selector class, the onmatch will be called and you can initialize your component there.

Since you didn't specify what exactly you're trying to achieve, it's hard to give better guidance. I think this is also a pretty good read, if you're new to entwine: https://www.bigfork.co.uk/takeaway/a-beginners-introduction-to-using-entwine-in-silverstripe