0

我正在制作我的第一个文件上传器 jquery 插件(在 coffeescript 中):

    $.fn.uploadable = (opts={}) ->
      console.log $(@).attr('type') # undefined
      event = if $(@).attr('type') is 'file' then 'change' else 'drop'
      @
      .on event, (evt) ->
        # do something
        off
      .on 'dragover', (evt) -> off


    $('#files_input, #drop_zone').uploadable

所以你可以看到,在第一个 .on() 中,我正在确定事件的元素是否是浏览文件按钮;如果是,那么当用户选择文件时,该元素将被监听“更改”事件,如果否,那么我认为它是一些普通的旧 div 或用于 HTML5 拖放操作的东西。

所以我在一个 INPUT 元素和一个 DIV 元素上使用插件。正如您从我的 console.log 中看到的那样,记录了“未定义”

到目前为止,我只知道像 attr() 这样的调用方法,您只能从列出的选择器元素之一中获得结果。但是我需要为每个匹配的元素单独设置 .on(event) 的事件变量。我怎样才能做到这一点?

谢谢

4

1 回答 1

0

通常的插件模式看起来像这样:

$.fn.plugin = function(options) {
    options = $.extend({ }, $.fn.plugin.defaults, options || { });
    return this.each(function() {
        // Do things to $(this) to set up your plugin.
    });
};
$.fn.plugin.defaults = { ... };

CoffeeScript 版本是:

$.fn.plugin = (options = { }) ->
    options = $.extend({ }, $.fn.plugin.defaults, options)
    @.each ->
        # Do things to $(@) to set up your plugin
$.fn.plugin.defaults = { ... }

return部分return this.each是为您提供通常的链接,this.each部分是允许插件一次绑定到多个东西的部分。

应用这个你的案例会给你:

$.fn.uploadable = (opts = { }) ->
  @.each ->
    event = if $(@).attr('type') is 'file' then 'change' else 'drop'
    $(@)
      .on event, (evt) ->
        # do something
        off
      .on 'dragover', (evt) -> off
于 2012-05-31T03:16:26.153 回答