Javascript Moodle - javascript

Hi I am fairly new to moodle. I have been trying to test if my Javascript runs but to no avail. Here is what I have:
In /videojs/amd/src I made a test.js file with a simple command
define(['jquery'], function() {
return {
init: function() {
// Put whatever you like here. $ is available
// to you as normal.
alert("It changed!!");
}
};
});
Then I grunt the file and everything succeed, and made minified. But when I go to the page it doesn't run. Now I read Moodle's Javascript Doc and I see it says
The idea here is that we will run the 'init' function from our (PHP) code to set things up. This is called from PHP like this...
Where do I call this PHP?

Somewhere in the page you are outputting, you need to add a call like this:
$PAGE->requires->js_call_amd('PLUGINTYPE_videojs/test', 'init);
It's not entirely clear from your example what sort of plugin you are creating, so whichever type you are creating (https://docs.moodle.org/dev/Plugin_types), you need to put it in the appropriate subdirectory for your site (e.g. /mod/videojs, /local/videojs, etc.), then add some sort of PHP script as the entry point for your plugin and call the js_call_amd function from there.

Related

How to call a function with in same java script file

I am writing Automation scripts using protractor. I have created a java script file in which I have created a function.
PlatformviewCnOPage is my JS file and searchCapabilityOfferingsName is function. I want to call this function in another function (in same file).
var PlatformviewCnOPage = function() {
this.searchCapabilityOfferingsName = function(){
coreutil.clickElement(objectrepo.platformView_Searchbox_EnterBtn,'xpath');
browser.sleep(2000);
var searchResult= coreutil.getTextofElement(objectrepo.platformView_SearchResult,'xpath');
return searchResult;
}
I want to use the above function i.e searchCapabilityOfferingsName in another function in same java script file. I have tried some combinations but its not working.Basically I am new to java script.
this.verifySearchinCnO = function(){
this.searchCapabilityOfferingsName();// Failed-method not defined
searchCapabilityOfferingsName(); //Failed method not defined
Create object of same file and call the function. // Failed.
}
};
module.exports = PlatformviewCnOPage;
Could anyone suggest how can I call the function in another function in same JS file?
PlatformviewCnOPage is defined as object/function which contains the method searchCapabilityOfferingsName.
So you can easily call PlatformviewCnOPage.searchCapabilityOfferingsName()
There should be some mistake in your PlatformviewCnOPage.js which lead to some definitions missing even loaded by require.
You can try below steps to figure out the wrong place:
Step 1 comment out other codes only except function: verifySearchinCnO and searchCapabilityOfferingsName
Step 2 add a console.log(xxx) as first line of the function: verifySearchinCnO and searchCapabilityOfferingsName
Step 3 run your test script again, if the both console.log(xxx) print out, means the wrong place in functions you commented out, then remove comment of some code lines and run test script again until find the correct place.

Running client side javascript without loading a new (blank) view on Odoo 8

I need to run some client-side javascript from a button in a form view in Odoo 8. This button runs a python method which returns this dictionary:
{"type": "ir.actions.client",
"tag": "my_module.do_something",}
do_something is defined in a .js file as follows:
openerp.my_module = function (instance) {
instance.web.client_actions.add("my_module.do_something", "instance.my_module.Action");
instance.my_module.Action = instance.web.Widget.extend({
init: function() {
// Do a lot of nice things here
}
});
};
Now, the javascript is loaded and executed properly, but even before launching the init function, Odoo loads a brand new, blank view, and once the javascript is over I can't get browse any other menu entry. In fact, wherever I click I get this error:
Uncaught TypeError: Cannot read property 'callbackList' of undefined
What I need instead is to run the javascript from the form view where the button belongs, without loading a new view, so both getting the javascript stuff done and leaving all callbacks and the whole environment in a good state. My gut feeling is that I shouldn't override the init funcion (or maybe the whole thing is broken, I'm quite new to Odoo client-side js) , but I couldn't find docs neither a good example to call js the way I want. Any idea to get that?
Sorry, I don't work on v8 since a lot of time and I don't remember how to add that, but this might help you: https://github.com/odoo/odoo/blob/8.0/doc/howtos/web.rst
Plus, if you search into v8 code base you can find some occurence of client actions in web module docs https://github.com/odoo/odoo/search?utf8=%E2%9C%93&q=instance.web.client_actions.add
Thanks to the pointers simahawk posted in another answer, I have been able to fix my js, which is now doing exactly what I needed. For your reference, the code is as follows:
openerp.my_module = function (instance) {
instance.web.client_actions.add("my_module.do_something", "instance.my_module.action");
instance.my_module.action = function (parent, action) {
// Do a lot of nice things here
}
};

Qt function runJavaScript() does not execute JavaScript code

I am trying to implement the displaying of a web page in Qt. I chose to use the Qt WebEngine to achieve my task. Here's what I did :
Wrote a sample web page consisting of a empty form.
Wrote a JS file with just an API to create a radio button inside the form.
In my code, it looks like this :
View = new QWebEngineView(this);
// read the js file using qfile
file.open("path to jsFile");
myJsApi = file.Readall();
View->page()->runjavascript (myjsapi);
View->page()->runjavascript ("createRadioButton(\"button1\");");
I find that the runJavaScript() function has no effect on the web page. I can see the web page in the output window, but the radio button I expected is not present. What am I doing wrong?
I think you will have to connect the signal loadFinished(bool) of your page() to a slot, then execute runJavaScript() in this slot.
void yourClass::mainFunction()
{
View = new QWebEngineView(this);
connect( View->page(), SIGNAL(loadFinished(bool)), this, SLOT(slotForRunJS(bool)));
}
void yourClass::slotForRunJS(bool ok)
{
// read the js file using qfile
file.open("path to jsFile");
myJsApi = file.Readall();
View->page()->runJavaScript(myjsapi);
View->page()->runJavaScript("createRadioButton(\"button1\");");
}
I had this problem, runJavascript didn't have any effect. I had to put some html content into the view (with page().setHtml("") before running it.
Check the application output, it might contain JavaScript errors. Even if your JS code is valid, you might encounter the situation where the script is run before DOMContentLoaded event, that is document.readyState == 'loading'. Therefore, the DOM might not be available yet, as well as variables or functions provided by other scripts. If you depend on them for your code to run, when you detect this readyState, either wait for the event or try calling the function later, after a timeout. The second approach with timeout might be needed if you need to get the result of the code execution, as this can be done only synchronously.

Include a javascript file only once in Joomla

now, this question has been asked and answered successfully many times, yet none of the things i try work.
I have tried head.js & require.js libraries
I have also tried
if (!window.unique_name) {
unique_name = true;
//code here..
}
none of which I can get to work (the global variable is always undefined)
the script I am trying to include runs something like this:
//clock.js
clockyTick = function() {
//my code here
}
setInterval(clockyTick, 1000);
the apps that call this script, standalone, work fine.
only when both apps are included on the same page (via calls to PHP require()) they break.
Here is the cause of the problems (I think):
I am building custom web apps on a (Joomla) site and have the requirement of displaying two of my apps on the same page.
Both apps need the same .js file to operate correctly, which works fine when they run standalone, but as soon as both apps are running on the same page (in the admin section) the scripts conflict and stop each other from working
(the script in question is a dynamic clock script that grabs the specialised contents of a div and modifies it to something else)
I think the reason I cannot get aforementioned libraries to work, is the fact that they also are being included twice on the admin page.
is there any way around this, or do I have to bite the bullet and integrate a library into the main Joomla template? (meaning the library is uselessly loaded on every single page, yet only used on 3 of hundreds)
jQuery is also required, separately, on each app..but thankfully I am able to use noConflict to avoid problems there (not ideal)
The joomla way would be to instantiate the document inside your module and unset only the conflicting script as described in this question here just before you load the module's script:
1) get an instance if the document object and remove the js files (you
could do that in a plugin) :
<?php
//get the array containing all the script declarations
$document = JFactory::getDocument();
$headData = $document->getHeadData();
$scripts = $headData['scripts'];
//remove your script, i.e. mootools
unset($scripts['/media/system/js/mootools-core.js']);
unset($scripts['/media/system/js/mootools-more.js']);
$headData['scripts'] = $scripts;
$document->setHeadData($headData);
?>
Or in your case, I think you could try the dirty solution below inside your js files:
//1st module script
var unique_name;
if (unique_name == false || unique_name == null) {
unique_name = true;
//code here..
alert("Included 1st script");
}else{
//do nothing
alert("Not included 1st script")
}
//2nd module script
var unique_name;
if (unique_name == false || unique_name == null) {
unique_name = true;
//code here..
alert("Included 2nd script");
}else{
//do nothing
alert("Not included 2nd script")
}
Here is a DEMO
If you are having conflicts with PHP require(), you can try require_once(). However, as mentioned, that’s not the Joomla way of doing things.

What's the best way to execute something only when all my JavaScript is loaded using jQuery?

I'm developing a web page using jQuery, and I want it to execute some code only after ALL my JavaScript files are fully loaded. The head section of my HTML has the following script.
<script src="supervisor/lib/jquery-1.6.min.js" type="text/javascript"></script>
Inside jQuery file, I inserted the following code:
$.getScript('functions.js', function () {
// code here
});
The file functions.js has the following code:
$.getScript('mask.js');
$.getScript('validations.js');
$.getScript('lotsofscripts.js');
// and more...
I want the code here in the first $.getScript() to execute only after ALL the other JS are loaded, but this is not ocurring. What's the best way to achieve this?
PS: I'm using lots of $.getScript() because I find easier to separate them, but I want them to be inserted inside the same file.
You could always just increment a counter. That way your getScript calls remain asynchronous, as the last thing you want to do is change that. And frankly, any packaged solution you find to loading the scripts in parallel and then executing some function afterward will probably just be a shinier version of this:
var counter = 0;
var filesToLoad = ["mask.js", "validations.js", "lotsofscripts.js"];
var filesCount = filesToLoad.length;
// Increment counter each time a getScript completes
function incrementCounter() {
if (++counter === filesCount) {
// This code will execute after everything loads
}
}
// Iterate through the files and run getScript on them,
// with incrementCounter as the callback
for (var i = 0; i < filesCount; i++) {
$.getScript(filesToLoad[i], incrementCounter);
}
Here's a jsFiddle example.
Assuming you know the name of a function defined in a js script that needs to be tested for whether or not it has loaded...
I use Underscore.js isFunction() to figure this out ( http://documentcloud.github.com/underscore/#isFunction )
Example, if script.js contains a function myScriptFunction(), you can write a function that checks:
if (_.isFunction(myScriptFunction)) {
// script.js is loaded
// OK to move on to the next step
} else {
// script.js is not loaded
// check again later
}
I have tried binding to events to figure out if a js script file is loaded, but it doesn't seem to work across all the browsers.
I would suggest HeadJS to load your JS files. You can execute specific code upon completion of specific files or groups of files. Take a look, it's a great little project.
You might want to use jQuery.ajax() instead. You can set the async option to false (it's true by default when you use getScript

Categories

Resources