使用带有Backbone和Requirejs的jQuery插件

Maj*_*jdi 7 javascript jquery jquery-plugins requirejs backbone.js

我正在使用backbone + requirejs + jquery,我在当前的html页面(精确的主干html模板)中加载了jquery插件有问题.

有我的要求配置:

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']  
  }
});
Run Code Online (Sandbox Code Playgroud)

在我的布局html页面中,我有:

<script type='text/javascript' src='/js/jquery/jquery.camera.js'></script>
Run Code Online (Sandbox Code Playgroud)

在我的模板页面中,我有:

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

    jQuery('#test').camera({
...
</script>
Run Code Online (Sandbox Code Playgroud)

最后我的浏览器消息:

Uncaught TypeError: Object [object Object] has no method 'camera'
Run Code Online (Sandbox Code Playgroud)

你有什么主意吗?

同时我还有另一个问题,在我们当前页面中包含一些js代码的最佳方法是使用backbone,requirejs等.

谢谢 :)

Cri*_*tes 18

我解决了类似的问题(Jquery.cookie),但我的问题是Jquery正在加载,然后Jquery.cookie被包含但需要已经有JQuery作为静态资源.

所以像这样我将Jquery.Cookie传递给应用程序,它只在我的应用程序范围中插入jquery.cookie.

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']
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

然后在我添加的主App类中

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

在此之后,我能够找到jquery cookie.

顺便说一句:如果您使用Require.js来获取它,则无需在您的html中导入JQuery.camera,除非您在Require.js范围之外使用它.