【问题标题】:Placement for jQuery plugin within a custom jQuery plugin在自定义 jQuery 插件中放置 jQuery 插件
【发布时间】:2018-03-23 08:48:44
【问题描述】:

我有一个基于this boilerplate 的小插件。

一切正常,但希望专注于在插件中放置一个小的“帮助”功能。这是sn-p。

(function ($, window, document, undefined) {
	
    var pluginName = 'test',
		defaults = {};
	
    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this.init();
    }

    Plugin.prototype = {
        init: function() {
            $(this.element).find(':input').each(function() {
				$(this).setValue('value');
			});
        }
    };
	
	$.fn.setValue = function(value) {
		var $el = $(this);
		if ($el.prop('type') == 'checkbox') {
			$el.prop('checked', true);
		} else {
			$el.val(value);
		}
	};
	
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin( this, options ));
            }
        });
    };

})(jQuery, window, document);

$('#apply-test').click(function(e) {
	e.preventDefault();
	$('#test').test();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container mt-5">
    <form id="test">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" name="name" id="name" class="form-control">
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="text" name="email" id="email" class="form-control">
        </div>
        <div class="form-group">
            <div class="form-check">
                <input type="checkbox" name="notifications" id="notifications" class="form-check-input">
                <label for="notifications" class="form-check-label">
                    Receive Notifications
                </label>
            </div>
        </div>
        <div class="form-group">
            <button type="submit" id="apply-test" class="btn btn-primary">Apply Test</button>
        </div>
    </form>
</div>

在插件中,您会注意到另一个类似这样的功能:

$.fn.setValue = function(value) {
    var $el = $(this);
    if ($el.prop('type') == 'checkbox') {
        $el.prop('checked', true);
    } else {
        $el.val(value);
    }
};

现在我可以将该代码放置在该插件内部或外部的任何我喜欢的位置,并且它工作得很好。另外,我使用这样的函数的原因是我可以在设置表单元素值时轻松使用它,其方式与使用标准 $(el).val() 几乎相同。

我的问题如下:

  • 是否可以通过某种方式对其进行设置以使该函数成为私有函数?
  • 如果不是,则将其放在函数中,就像在 摆弄一个好的方法来添加一些小助手功能,比如 这个?
  • 或者有其他推荐的方法吗?
  • 或者也许像这样的助手应该只是他们自己的独立 插件? (这里可能只是一个偏好)

【问题讨论】:

  • 这个断言正确吗? «你需要函数setValue只能从你的插件中访问。»
  • 嗯,我不需要它,我只是想知道是否有办法这样做。只是想学你知道..
  • 该功能仅用于插件本身的功能。
  • 所以我的建议是:你最好坚持我的回答。

标签: javascript jquery jquery-plugins


【解决方案1】:

问题是一旦$.fn.setValue = function … 被执行,setValue 函数就可以在你的应用程序的任何地方被调用(比如$('randomSelector').setValue()),这可能不是你的意图。

要使setValue 函数只能在您的插件中访问,您可以使其行为依赖于提供的参数:

(function ($, window, document) {
    // …
// Make setValue only accessible through the plugin
    function setValue = function(value) {
      if (this.prop('type') == 'checkbox') {
        this.prop('checked', true);
      } else {
        this.val(value);
      }
    };

    $.fn[pluginName] = function(options, more) {
// Test arguments and call setValue when appropriate
      if (options === 'set') {
        // Apply setValue on the current jquery Collection
        setValue.apply(this, more);
        // Make your plugin "chainable"
        return this;

      // Eventually handle other scenarios
      } else /* if (…) */ { ; }

      // Your default plugin behavior
      return this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
          $.data(this, "plugin_" + pluginName,
            new Plugin(this, options));
        }
      });
    };

})(jQuery, window, document);

然后你这样调用你的插件:

$('#apply-test').click(function(e) {
  e.preventDefault();
  // Call setValue
  $('#test').test('set', 1);
  // Standard call
  $('#test').test();
});

旁注:在插件函数$.fn.xxx = function() {/*here*/} 中,this 指向触发插件函数调用的 jquery 集合。所以var $el = $(this); 在这种情况下是没用的(它只会增加开销),只需使用this 或最终使用this.eq(0) 或this.each(…)。

【讨论】:

  • 啊,谢谢您在$.fn.xxx 中提供有关this 的提示!我之前并没有真正注意到这一点。但是在示例中将函数留在现在所在的位置并没有什么害处吗?我一直在寻找其他插件,看看它们中是否有任何一个做同样的事情,但我还没有真正找到,所以我问..谢谢!
  • @Rick $.fn.setValue = function … 的问题是 setValue 可以在您的应用程序中随时随地使用$('randomSelector').setValue() 调用,这可能不是您的意图。只有“整个”插件应该放入$.fn 命名空间。另一方面,辅助函数应该包含在适当的命名空间中。经验法则:依赖于特定辅助函数的上下文越少,它就越需要“私有化”。
  • @Rick 考虑通过勾选答案将您的问题标记为已回答/已解决。
  • 好吧,它确实没有回答我的问题,但我想它让我得到了无法完成的答案,我很欣赏$.fn.xxx 中关于this 的提示,所以我会接受。
  • 我的回答告诉您,您的代码实际上不会使 setValue 私有(相对于插件定义),因为将其设置为 $.fn 的属性也使得该函数几乎可以从任何地方调用。为了使其私有并避免误用,只需像我在 sn-p 中那样定义它。
猜你喜欢
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多