Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - RequireJs - Define vs Require

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):

require(['jquery'], function($) {
    $.fn.myPlugin = function(options) {
        ...
    };
});

Now if I say the following in another module:

require(['jquery', 'jquery.my-plugin'], function($) {
    $('#element').myPlugin();
});

I've found this doesn't work because myPlugin has not been registered. However if I change the require to a define within my jquery.my-plugin module then it works fine.

I'd appreciate it if someone could clear up why I have to do this. I like to understand something fully before I go ahead and use it. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Essentially, when you use require you are saying "i want this, but i want all its dependencies too". So in the example below, we're requiring A, but require will search for all dependencies and ensure they are loaded before continuing.

require(['a'], function(a) {
    // b, c, d, e will be loaded
});

// File A
define(['b','c','d','e'], function() {
    return this;
});

General rule of thumb is you use define when you want to define a module that will be reused by your application and you use require to simply load a dependency.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...