0

我有一个 javascript 文件,用户可以将其嵌入到他们的网站上。它使用 coffeescript 和 Rails 资产管道将一堆文件编译成一个。

# The following dependencies will be compiled into test.js (rails asset pipeline manifest file)
#
#= require jquery
#= require jquery.cookie

jQuery ->
  $.cookie('foo', 'bar')
  console.log $.cookie('foo')

这可以使用示例页面按预期工作:

<!DOCTYPE html>
  <head></head>
  <body>
    <script src="http://localhost:3000/assets/test.js" type="text/javascript"></script>
  </body>
</html>

但是这个脚本是一个小部件,所以它应该可以嵌入到任何网站上。如果用户在它下面添加自己的 jquery,那么事情就会中断:

<!DOCTYPE html>
  <head></head>
  <body>
    <script src="http://localhost:3000/assets/test.js" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  </body>
</html>

这给出了错误Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'cookie'

将所有内容都包含在 test.js 中以便自包含的最佳方法是什么?我认为将所有内容包装在匿名函数中的咖啡脚本在这里可能会有所帮助,但我想不会。

谢谢!

4

1 回答 1

0

本教程提供了一些线索:http ://alexmarandon.com/articles/web_widget_jquery/

听起来我可能必须在匿名函数中包含插件(如 jquery.cookie)的缩小源代码。资产管道不允许您要求这样的语句,除非它们位于文件顶部(在第一个注释块中):https ://github.com/sstephenson/sprockets/issues/398

于 2012-12-15T22:00:37.127 回答