【发布时间】: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