Adding jQuery Plugin to Backbone + require.js code

I had BackboneJs + jquery code, which I am now trying to modulate with requireJs. In my code I use additional jquery plugins like nanoscroller etc.

Previously, you just need to call the script:

<script type="text/javascript" src="../javascript/jquery.nanoscroller.js"></script> 

Now I am trying to call the script by:

 define([ 'jQuery', 'Underscore', 'Backbone', 'text!templates/landingTemplate.html', 'library/jquery/jquery.nanoscroller.js' ], function($, _, Backbone, LandingTemplate){ var LandingView = Backbone.View.extend({ 

But I get the following error:

 Error: jQuery is not defined Source File: http://localhost:8080/sample/Main%20App/Backbone%20+%20Require.js%20Impl/js/library/jquery/jquery.nanoscroller.js 

I tried a couple of things: Using "require" instead of "define", but that didn't work. I'm not sure what I am missing here. Please help.

Thanks, Komal.

+4
source share
2 answers

The error was not due to an incorrect jQuery definition. This was because the media library was loaded before jQuery was. The solution used the "order" plugin to make sure jQuery was loaded before loading the nanoscaler library. This is why the problem is resolved for me:

 require(['order!jQuery', 'order!library/jquery/jquery.nanoScroller'], function ($) { $("#myFields").nanoScroller(); } 
+2
source

jQuery actually defines itself as a named module:

 define( "jquery", [], function () { return jQuery; } ); 

Usually, you are not recommended to add your own module names, but in the case of jQuery you just need to tell RequireJS where to find the library using the path configuration:

 require.config({ paths: { jquery: 'lib/jquery', } }); 

This will allow you to simply use jquery in your require and define calls.

There are several ways to configure RequireJS that you can read in API docs .

+2
source

Source: https://habr.com/ru/post/1411473/


All Articles