Komal
Komal

Reputation: 73

Adding Jquery Plugin to Backbone + require.js code

I had a BackboneJs + jquery code which now I am trying to modularize using requireJs. In my code I am using additional jquery plugins like nanoscroller etc.

Earlier just calling the script was enough:

<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 am getting 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 have tried couple of things: Using "require" instead of "define" but it didnt work. I am not sure what am I missing here. Kindly Help.

Thanks, Komal.

Upvotes: 4

Views: 1969

Answers (2)

Komal
Komal

Reputation: 73

The error was not because the Jquery was not properly defined. It was because the nanoscroller library was getting loaded before jQuery was. The solution was use the "order" plugin to make sure jQuery is loaded before the nanoscroller library is loaded. Following is how the issue got resolved for me:

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

Upvotes: 2

Simon Smith
Simon Smith

Reputation: 8044

jQuery actually defines itself as a named module:

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

Normally you are discouraged from adding your own module names, but in the case of jQuery you simply need to tell RequireJS where to find the library by using the paths configuration:

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

That should allow you to just use jquery in your require and define calls.

There is more than one way to configure RequireJS, which you can read about in the API docs.

Upvotes: 2

Related Questions