【问题标题】:Use jQuery plugin with Backbone and Requirejs使用带有 Backbone 和 Requirejs 的 jQuery 插件
【发布时间】:2012-10-11 13:53:28
【问题描述】:

我正在使用主干+requirejs+jquery,但在我当前的 html 页面中加载 jquery 插件时遇到问题(确切地说是主干 html 模板)。

有我需要的配置:

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']  
  }
});

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

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

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

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

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

最后是我的浏览器消息:

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

你有什么想法吗?

同时我还有一个问题,在我们当前的页面中包含一些 js 代码的最佳方式是什么,包括主干、requirejs 等。

谢谢:)

【问题讨论】:

  • 能否提供完整代码?您可以为此使用 jsfiddle.net。似乎未加载 jquery 相机插件。由于浏览器下载组件的方式,放置 JS 脚本的最佳位置是在页面底部。

标签: javascript jquery jquery-plugins backbone.js requirejs


【解决方案1】:

我解决了类似的问题(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']
    }
  }
});

然后在我添加的主 App 类中

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

在此之后我能够找到 jquery cookie。

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

【讨论】:

  • 非常感谢。我已经在网上搜索了大约 2 个小时,试图弄清楚这一点。我唯一需要做的就是将“jquery.cookie”添加到主 App 类中。但是我觉得应该有一个更好的方法来加载 jQuery 插件,我真的不喜欢有 5 个参数进入 require() 并且只有 4 个被发送到函数......但是这个实现现在完美地工作.谢谢!
  • 你甚至不需要 jquery-cookie 的 shim 配置,因为它是一个与 AMD 兼容的模块并且它自己需要 jquery
  • 太棒了。他们真的应该在 require.js 站点上记录这个......我尝试了一些接近这个的东西,但没有将非导出模块放在我的依赖项列表的末尾,并且搞砸了我其他部门的排序。谢谢,+1
猜你喜欢
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多