Use jQuery plugin with Backbone and Requirejs

I'm working with backbone+requirejs+jquery and I have a problem with jquery plugin loading in my current html page (backbone html template precisly).

There is my require configuration:

require.config({

  paths: {
    // ... some code about backbone config
    jquery: '/js/lib/jquery/jquery.min',
    'jquery.camera' : '/js/jquery/jquery.camera'
  },

  shim: {
    // ... some code about backbone config
    'jquery.camera': ['jquery']  
  }
});

In my layout html page I have:

<script type='text/javascript' src='/js/jquery/jquery.camera.js'></script>

and in my template page I have:

<script type="text/javascript">
  jQuery(function() {

    jQuery('#test').camera({
...
</script>

Finally my browser mesg :

Uncaught TypeError: Object [object Object] has no method 'camera'

Do you have any idea?

In the same time I have another question, what is the best way to include some js code in our current page with backbone,requirejs, etc.

Thanks :)

Answers:

Answer

I solved a similar issue (Jquery.cookie) like this, but my problem was that Jquery was being loaded and then Jquery.cookie was being included but require already had JQuery as a Static resource.

So like this I pass Jquery.Cookie to the application and it inserts jquery.cookie in my application scope only.

require.config({

  paths: {
      'async'           : 'libs/async'
      ,'jquery'         : 'libs/jquery'
      ,'underscore'     : 'libs/underscore'
      ,'backbone'       : 'libs/backbone'
      ,'text'           : 'libs/text'
      ,'jquery.cookie'  : 'libs/jquery.cookie'   // <-- cookie lives here
  }

  ,shim: {
    'jquery': {
      exports: '$'
    }
    ,'underscore': {
      exports: '_'
    }
    ,'backbone': {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone'
    }
    ,'jquery.cookie': {     //<-- cookie depends on Jquery and exports nothing
        deps: ['jquery']
    }
  }
});

and then in the main App class I added

require([
  'jquery'
  ,'underscore'
  ,'backbone'
  ,'mapApp'
  ,'jquery.cookie'   //<- this is the real trick !!!
],
  function ($, _, Backbone, App) {

After this I was able to find jquery cookie.

BTW: there is no need to import JQuery.camera in your html if you are using Require.js to fetch it, unless you use it outside your Require.js scope.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.