The javascript example in the doc is not working

The javascript example in the doc is not working

by Guirec Corbel -
Number of replies: 3
Hello,


I'm following this guide : http://docs.moodle.org/dev/JavaScript_guidelines . I have a file called `blocks/fruit/yui/fruitbowl/fruitbowl.js` and I added :


    $PAGE->requires->yui_module('moodle-block_fruit-fruitbowl', 'M.block_fruit.fruitbowl.init');

    $PAGE->requires->string_for_js('example', 'block_fruit');


In the javascript console I have "Uncaught TypeError: Cannot read property 'fruitbowl' of undefined". 


Did I missing something?


Thanks.

Average of ratings: -
In reply to Guirec Corbel

Re: The javascript example in the doc is not working

by Davo Smith -
Picture of Core developers Picture of Peer reviewers Picture of Plugin developers

That should work, however, if you're using Moodle 2.5 or above, you really should consider using Shifter instead ( http://docs.moodle.org/dev/Javascript/Shifter ).

What is inside your 'fruitbowl.js' file? Does it define the function M.block_fruit.fruitbowl.init?

e.g.

M.block_fruit = M.block_fruit || {};
M.block_fruit.fruitbowl = {
  init: function() {
    // Do some initialisation.
  }
}


In reply to Davo Smith

Re: The javascript example in the doc is not working

by Guirec Corbel -

This is a cut and paste of the example in the doc. So I have this in the js file :

YUI.add('moodle-core-foo',function(Y){
M.core_foo={
init:function(){
Y.one('#button').on('click',this.display_dialogue,this);
},
display_dialogue:function(e){
// Prevent the default link action.
e.preventDefault();

// Load the bar dependency.
Y.use('moodle-core-bar',function(){
var bar =new M.core_bar();

// Now that bar has been loaded, overwrite this function with the one provided by bar so that this function is no longer called, and execute it.
this.display_dialogue= bar.display_dialogue();
this.display_dialogue(e);
});
}
};
},'@VERSION@',{ requires:['node']});

In reply to Guirec Corbel

Re: The javascript example in the doc is not working

by Davo Smith -
Picture of Core developers Picture of Peer reviewers Picture of Plugin developers

Well you've tried to call a function called 'M.block_fruit.fruitbowl.init', but the only init function you have defined is 'M.core_foo.init'.

The examples in those docs are designed to convey the basic layout of the javascript within your code, they are clearly not designed to be copied and pasted and used directly (however, if you really want to copy and past from the docs, you could try scrolling down a bit further and using the dummy code that is relevant to the 'fruitbowl' naming example - i.e. the code that has  'moodle-block_fruit-fruitbowl' on the first line).

Average of ratings: Useful (1)