【问题标题】:Access method of jquery/coffeescript plugin from outside the pluginjquery/coffeescript插件从插件外部访问方法
【发布时间】:2012-04-25 00:02:24
【问题描述】:

我知道这个问题已经被问过好几次了,但是所有的答案都让我感到困惑,因为我不确定如何让咖啡脚本代码编译成指定的 jquery 代码。

这是我目前所拥有的:

pluginName = 'tagbox'

states = 
  none: 0
  typing: 1
  altering: 2        

defaults =
  editing: true
  tags: []

class Plugin
  constructor: (@element, options) ->
    @options = $.extend {}, defaults, options
    @_defaults = defaults
    @_states = states
    @state = states.none
    @_name = 'tagbox'
    @currentTag = $("<div class='ui-individualtag'></div>")

  # this is the public method I want
  setCurrentTag: (tagText) ->
    @currentTag.text(tagText)

$.fn[pluginName] = (options) ->
  @each ->
    if !$.data(this, "plugin_#{pluginName}")
      $.data(@, "plugin_#{pluginName}", new Plugin(@, options))
)(jQuery, window, document)

然后在另一个脚本中,我希望能够像这样访问 setCurrentTag 方法:

tagbox = $('#tagbox').tagbox()
tagbox.setCurrentTag("hello world")

让我知道它是否有助于在 jquery 中显示它编译成的内容。

【问题讨论】:

  • @RicardoTomasi:还有 jQuery-UI 风格的 $(x).tagbox('setCurrentTag', 'hello world')。这是我见过的最接近标准方法的方法,并且在保留链接的同时避免污染命名空间。
  • @muistooshort 是的,但他要求另一个。无论哪种方式都是一团糟:)

标签: jquery function plugins coffeescript public


【解决方案1】:

你的问题是tagbox:

tagbox = $('#tagbox').tagbox()

将是一个 jQuery 对象,并且没有 setCurrentTag 方法。您不想尝试更改它,因为这会破坏通常的 jQuery 链接行为。解决此问题的一种方法是为tagbox 插件提供足够的智能来解析其参数,以便您可以在其中传递方法名称:

$('#tagbox').tagbox('setCurrentTag', 'hello world')

这是jQuery-UI 采用的方法,所以很多 jQuery 人应该都熟悉它。

您需要做的就是修改您的$.fn.tagbox 使其看起来更像这样:

$.fn[pluginName] = (options = {}) ->
  if $.isPlainObject options
    @each ->
      if !$.data(@, "plugin_#{pluginName}")
        $.data(@, "plugin_#{pluginName}", new Plugin(@, options))
  else
    args = Array.prototype.slice.call(arguments);
    @each ->
      p = $.data(@, "plugin_#{pluginName}")
      p[args[0]](args[1])

演示:http://jsfiddle.net/ambiguous/q2U7d/

注意事项:

  1. 我添加了一个默认值 ((options = {}) -&gt;),以便 options 始终存在。
  2. 我们可以使用$.isPlainObject 检查我们是否有一个选项对象,如果没有选项,那么我们可以假设我们正在执行一个方法调用。这就是为什么我们希望在 1 中使用默认值。
  3. 我们使用Array.prototype.slice.call 将类似数组的arguments 转换为真正的数组,使其更易于使用。我们不必这样做,但如果我们想使用 Array 方法(例如 pop)并且我们需要在 @each 回调中引用外部 arguments,它可以避免一些混乱:arguments就像 this 在 (Coffee|Java)Script 中一样,是上下文相关的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2015-03-06
    相关资源
    最近更新 更多