Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  147] [ 3]  / answers: 1 / hits: 31110  / 11 Years ago, fri, june 28, 2013, 12:00:00

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


More From » requirejs

 Answers
13

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.


[#77338] Thursday, June 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adrienkeithr

Total Points: 503
Total Questions: 126
Total Answers: 110

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;