【发布时间】:2019-08-02 15:33:51
【问题描述】:
我正在使用下一个 jQuery 插件实现来定义我的插件。我已经使用 javascript 好几年了,但是 javascript 有很多惊喜。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
(function ($) {
// is using $.fn best practise / ok? or is something else better
// according to https://learn.jquery.com/plugins/basic-plugin-creation it's fine
$.fn.myPlugin = function () {
// private variables
var instance = this;
var privateVar1 = "some Value";
// private methods
var privateMethod = function(arg1) {
var bla = privateVar1;
if( arg1 > 0) {
arg1 -= 1;
// to call public method I just call:
instance.publicMethod(arg1);
}
};
// public methods start with this.
this.initialize = function () {
// this can refer to different things, depending on calling context
// https://stackoverflow.com/questions/3562980/javascript-this-value-changing-but-cant-figure-out-why
return this;
};
this.publicMethod = function(arg1) {
debugger;
// private methods are called only with the name
privateMethod(arg1);
};
return this.initialize();
}
})(jQuery);
$(document).ready(function() {
var a = $("#test").myPlugin();
a.publicMethod(1);
});
</script>
</head>
<body>
<div id="test">Test
<div id="test1"></div>
</div>
</body>
</html>
我想确保没有任何错误。例如,我知道 this 会根据上下文进行更改 (Javascript 'this' value changing, but can't figure out why) ... 我错过了什么吗?
我们的想法是以这样的形式编写自定义插件:
$("#myList").myCredentialsDialog();
$("#cars").carsGrid();
...
基本上这样每个自定义插件都可以使用这个template。模板表示var instance = this、this.publicMethod、var privateMethod = function() ...
【问题讨论】:
标签: javascript plugins jquery-plugins