javascriptjqueryjquery-pluginsrequirejsrequirejs-define

Using custom Jquery plugin with requireJS


sorry if I am repeating this question, but I am quite new in requireJS and I do not fully understand the way it works.

I am trying to implement amazon-like navigation with diagonal movement over elements. I found a jQuery plugin (https://github.com/kamens/jQuery-menu-aim) for that but I want to implement it with help of requireJS.

In common way you just include all necessary scripts with <script> tag (Jquery and the plugin). Then you find your navigation and assign some functions on activating/ deactivating submenu. Like example:

          <script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
            <script src="../jquery.menu-aim.js" type="text/javascript"></script>
            <script src="js/bootstrap.min.js" type="text/javascript"></script>
            <script>
                var $menu = $(".dropdown-menu");
                // jQuery-menu-aim: <meaningful part of the example>
                 // Hook up events to be fired on menu row activation.
               $menu.menuAim({
                    activate: activateSubmenu,
                    deactivate: deactivateSubmenu
                });

           function activateSubmenu(row) {//do something}
           function deactivateSubmenu(row) {//do someting else)
         </script>

In requireJS way. In the navigation.js file i required menu-aim plugin in the beginning and tried to implement it like this:

 var menuAim = require('lib/menu-aim');
 // some code
 var $menuT = $('#nav-main-deep');
 $menuT.menuAim({
        activate: activateSubmenu,
        deactivate: deactivateSubmenu

  });
   function activateSubmenu(){
        console.log('test1');
    }

    function deactivateSubmenu() {
        console.log('test2');
    }

And i put whole plugin menu-aim.js between:

define(function () {
//whole menu-aim plugin
});

Probably, this is not the way how to run requireJS plugin, cause its doing nothing (i tried to do some console logs). I tried to look at requireJS doc but I still dont understand how to do it right.. Will be very thankfull for advices..


Solution

  • From the GitHub code, it looks like jQuery-menu-aim is not using a universal module definition, so it needs some help from your RequireJS config.

    A shim can help RequireJS sequence the dependencies since this is a jQuery plugin and jQuery must be loaded first and passed into it. Click here for more information on RequireJS shims.

    Add this code to your RequireJS config file

    requirejs.config({
      shim: {
        'menu-aim': {
            deps: ['jquery']
        }
      }
    });
    

    and when you call

    require('lib/menu-aim', function() { 
      // put your menu code here 
    });
    

    jQuery and the menu plugin will be loaded.