1/07/2014

How to create AlloyUI reusable methods

When you are writing as much AlloyUI code as I do, you will certainly come to the situation where you want to reuse your code. Gladly, YUI3 (the foundation for AlloyUI) allows that. You can create your own modules and register them statically so you can call them from different parts of your application.


The key part is the "add" function.  It allows you to register your new module with all the methods, that you want to add. 

YUI.add('your-registered-module', function (A) {
  A.YourModuleObject = {
    yourMethod: function () {
      alert('Hello World');
  }
});

Do this at the beginning of your file and you can add your method in your code using this:
YUI().ready(
'your-registered-module',
  
  function(A) {
 A.one('#myButton').on('click', function(event) {
  A.YourModuleObject.yourMethod();
  });
Explanation: In this case we attach our hello world method to a button. When the button is clicked, our reusable method gets called and send the alert.

If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.