【发布时间】:2013-08-09 00:35:06
【问题描述】:
我习惯于通过包含离题和无用的咆哮来使问题变得不必要地冗长。这次我尽量不做。 对于缺少更好、更具描述性的标题,我深表歉意。
所以,这里有一个CoffeeScript 代码。
(($, window, document) ->
# Conventionally 'private' variables
_name = 'aPlugin'
_defaults =
property: 'value'
_debug = (args) ->
console.log args
return
# Plugin constructor
Plugin = (element, options) ->
@element = element
@options = $.extend true, {}, _defaults, options
@init()
return
# Initialization
Plugin.prototype.init = () ->
# Initialization logic here
_debug(@element) unless typeof(@element)=='undefined'
return
# Plugin wrapper, allowing for multiple instances
# and chainability
$.fn[_name] = (options) ->
return @.each (idx) ->
($.data @, 'plugin_' + _name
new Plugin @, options
) unless $.data @, 'plugin_' + _name
return
) jQuery, window, document
这是相同的代码,当编译(或转编译)为 JavaScript 时。
(function() {
(function($, window, document) {
var Plugin, _debug, _defaults, _name;
_name = 'aPlugin';
_defaults = {
property: 'value'
};
_debug = function(args) {
console.log(args);
};
Plugin = function(element, options) {
this.element = element;
this.options = $.extend(true, {}, _defaults, options);
this.init();
};
Plugin.prototype.init = function() {
if (typeof this.element !== 'undefined') {
_debug(this.element);
}
};
$.fn[_name] = function(options) {
return this.each(function(idx) {
if (!$.data(this, 'plugin_' + _name)) {
$.data(this, 'plugin_' + _name);
return new Plugin(this, options);
}
});
};
})(jQuery, window, document);
}).call(this);
而且,为了清楚起见,我这样称呼这个插件:
jQuery(document).ready(function($) {
$('#specialDiv').aPlugin({ aString: 'Hello world!', aNumber: 62742, aObject: { aString: 'Hello aPlugin!', aNumber: 6274210 } });
});
插件调用中的options 参数无关紧要。这是为了测试。
我有两个问题:
- 在翻译后的 JavaScript 中,预期的代码已自动包装在
(function(){}).call(this)中。我以前从未见过。它有什么作用?安全吗?更重要的是,它在某种程度上是一种编码标准吗(因为 CoffeeScript 正在这样做)。 这里要补充一点:我是 CoffeeScript 的新手,所以它可能是括号放错或其他什么的副产品。不过,它似乎并没有阻碍操作。 - 当代码执行时,我得到
<div id="specialDiv"> </div>。在代码中,您可以看到我调用了console.log(),调用者(应该是一个jQuery 对象)作为参数。它在哪里解开?
非常感谢您的宝贵时间。
【问题讨论】:
-
我编写了一个简单的 jQuery 插件模板/shell,您可能会觉得它很有用 请参阅 github.com/davesag/coffeescript-jquery-plugin-template 它包含 QUnit 测试,是 100% Coffeescript,并演示了如何使用 sourceMaps 生成缩小文件。
标签: jquery jquery-plugins coffeescript