Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading jquery plugins with require js

Tags:

I am new to require js, and the problem is I don't really understand how to load jQuery plugins.

I would like to load multiple plugins but I already have problems with the first one, with the chose plugin

js

//site full url var siteUrl = window.location.protocol+"//"+window.location.host + "/";  requirejs.config({     baseUrl: siteUrl + "assets/js",      paths: {         "jquery": "libs/jquery",         "jquery-ui": "libs/jquery-ui",         "bootstrap": "libs/bootstrap",         "scripts": "scripts",         "plugins": "plugins",     },  });  requirejs(['jquery', 'jquery-ui', 'bootstrap', 'plugins/chosen'], function($, chosen){     $('.chzn-select').chosen(); }); 

my test html

<select data-placeholder="Choose a country..." style="width:350px;" class="chzn-select">     <option value="">Test</option>     <option value="">Test</option>     <option value="">Test</option> </select> 

and when I try to load it I get the following error

TypeError: $ is not a function   ...tion(){"in"==self.hoverState&&self.show()},self.options.delay.show),void 0):self...  bootstrap.js (line 6)  TypeError: $(...).chosen is not a function   $('.chzn-select').chosen(); 

Could someone please point out what I am doing wrong?

like image 590
Side Avatar asked Feb 07 '13 16:02

Side


1 Answers

When you're loading your dependencies, requirejs loads them all concurrently. When you're getting that error, it means that your plugin is being loaded and executed before jQuery has been loaded. You need to set up a shim to tell requirejs that the plugin depends on jQuery already being loaded.

Also, most jQuery plugins are not AMD aware, so you'll also want to tell requirejs what to look for to tell it the script loaded correctly. You can do this with an 'exports' entry in your shim.

I don't believe jqueryUI is AMD-aware either, so an entry in the shim is probably in order for that too. I don't use bootstrap, so I'm not sure if you'll need anything there.

Here's a shim for your plugin and jQueryUI, add this to your call to requirejs.config:

shim: {     'plugins\chosen': {         deps: [ 'jquery' ],         exports: 'jQuery.fn.chosen'     },     'jquery-ui': {         deps: [ 'jquery' ],         exports: 'jQuery.ui'     } } 

You may still have some issues that I'm not seeing yet, but this should at least get you moving forward. Also, this is probably worth a read: http://requirejs.org/docs/api.html#config-shim. I would definitely recommend reading that whole page if you haven't yet.

like image 66
Waxen Avatar answered Sep 27 '22 20:09

Waxen