How To Use Javascript In Silverstripe Cms?
Solution 1:
the 'Behaviour.register' call you mention is definitly deprecated and no longer available in the core code, so the docs need an update here.
unfortunately, i couldn't find a documented way to replace this behaviour, but for now the following should work for you, based on the approach in the forum post you mentioned first hand:
find the 'initGoogleMaps.js' script added here:
functiongetCMSFields() {
Requirements::javascript('mysite/javascript/initGoogleMaps.js');
...
inside this script, remove the Behaviour.register...
block, and move the initialize
function outside document.ready (or simply remove the document.ready part), so initialize
is globally available (you might consider renaming it).
then, add the following inside getCMSFields
:
$fields->addFieldToTab('Root.Content', new LiteralField('js', '<script>initialize();</script>'));
this will ensure the initialize
function is called every time a page's 'edit view' is rendered inside the cms.
hth
Solution 2:
As mentioned by ben,
LeftAndMain::require_javascript('mysite/javascript/initGoogleMaps.js')
is more reliable than 'include-it when needed'. Why? Because Silverstripe uses Ajax, it is better to load any javascript or css on the first load, so that they are ready when you go to different model admin areas within the CMS in ajax-powered environment. Not loading at the start causes inconsistency and your js, css files will not be loaded when you don't hard-load that admin area.
From documentation: http://doc.silverstripe.org/framework/en/reference/requirements and http://api.silverstripe.org/3.0/class-LeftAndMain.html
The whole "include it when you need it" thing shows some weaknesses in areas such as the CMS, where Ajax is used to load in large pieces of the application, which potentially require more CSS and JavaScript to be included. At this stage, the only workaround is to ensure that everything you might need is included on the first page-load.
One idea is to mention the CSS and JavaScript which should be included in the header of the Ajax response, so that the client can load up those scripts and stylesheets upon completion of the Ajax request. This could be coded quite cleanly, but for best results we'd want to extend prototype.js with our own changes to their Ajax system, so that every script had consistent support for this.
By the way, the ideal place for this line is _config.php in your custom module or in mysite, depending on your needs.
Solution 3:
LeftAndMain::require_javascript('mysite/javascript/initGoogleMaps.js')
would work much better
Post a Comment for "How To Use Javascript In Silverstripe Cms?"