RequireJs - Define vs Require

后端 未结 2 683
慢半拍i
慢半拍i 2020-12-12 18:46

For modules I don\'t return an object I have been using require instead of define. For example say I have the following jQuery plugin (jquery.my-plugin.js):

         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 19:51

    Below is the code that should be inside jquery.my-plugin.js which defines a module called 'jquery.my-plugin' that can be used as a dependency elsewhere.

    define(['jquery'], function($) { //jquery is a dependency to the jquery.my-plugin module
        $.fn.myPlugin = function(options) { //adds a function to the *global* jQuery object, $ (global since jQuery does not follow AMD)
            ...
        };
    });
    

    Below is a section of code where you want to attach your plugin function to the global jQuery object and then use it ...

    require(['jquery.my-plugin'], function() { // jquery.my-plugin is loaded which attaches the plugin to the global JQuery object as shown above, then this function fires
    
        //the only reason $ is visible here is because it's global. If it was a module, you would need to include it as a dependency in the above require statement
        $('#element').myPlugin(); //the $ refers to the global object that has the plugin attached
    });
    

提交回复
热议问题