jquery - 如何在 CoffeeScript 中创建 jQuery 插件?

标签 jquery jquery-plugins coffeescript scope

关于How to Create a Basic Plugin有一个标题为保护 $ 别名并添加范围的部分。

The $ variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have to make jQuery not use the $ with jQuery.noConflict(). However, this will break our plugin since it is written with the assumption that $ is an alias to the jQuery function. To work well with other plugins, and still use the jQuery $ alias, we need to put all of our code inside of an Immediately Invoked Function Expression, and then pass the function jQuery, and name the parameter $:

在 JavaScript 中,这个包装器看起来像这样:

(function ( $ ) {
  // do stuff
  return this;
})(jQuery)

如何将其翻译成 CoffeeScript?

最佳答案

这个 CoffeeScript :

$ = jQuery
### do stuff ###

编译为:

// Generated by CoffeeScript 1.6.3
(function() {
  var $;
  $ = jQuery;
  /* do stuff*/
}).call(this);

我认为效果是相同的,确保 $ 指向 jQuery,无论调用环境中的 $ 是什么。

这是Coffeescript的作者在Writing a jquery plugin in coffeescript - how to get "(function($)" and "(jQuery)"?中推荐的

为了更接近原始模式(do 对我来说仍然是一个黑匣子)

do ($=jQuery) ->
  ### do stuff  ###
  @

“裸”编译为:

// Generated by CoffeeScript 1.6.3
(function($) {
  /* do stuff*/

  return this;
})(jQuery);

关于jquery - 如何在 CoffeeScript 中创建 jQuery 插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073154/

相关文章:

jquery - 如何向一个 jQuery 函数添加多个变量?

jquery - 如何删除页面中的样式表 CSS 文件并阻止它们被加载?

javascript - CoffeeScript 函数调用 - 参数和括号

javascript - 通知 : closable "false" not working?

javascript - underscore.js 中按日期对数组进行排序

coffeescript - Coffescript 如何访问其他 Assets 的功能?

javascript - jQuery Select2 - 选择 ajax 提交的值

jquery - 在 CSS Bootstrap jquery modal 中将元素暴露在模态背景之外

jquery - fancybox 似乎不适用于 ajax 内容

jquery - 如何重置 Jquery sumoselect 多选插件中的选择框值