我正在创建一个 jQuery 插件。到目前为止它工作正常,但我对我做事的方式有疑问:
jQuery.fn.myMethod = function() {
return this.each(function(){
MyScope.doSomething(jQuery(this).attr("id"));
});
};
var MyScope = {
// The functions contained in MyScope are extremely linked to the logic
// of this plugin and it wouldn't make a lot of sense to extract them
doSomething: function(id){
// something
doSomethingElse(23);
// some more code
doSomethingElse(55);
},
doSomethingElse: function(someInt){
// some code
}
};
我使用 MyScope 来存储我所有的“私有(private)”函数。我不希望用户能够使用 $("p").doSomething()
,但我确实需要使用它们。
我可以移动 myMethod
函数中的所有内容,但它会创建一个 100 行长的函数,人们会因此讨厌我。
在这种情况下,最佳做法是什么?有没有关于这方面的优秀教程?
最佳答案
你可以封装你的函数来做你想做的事,像这样:
jQuery.fn.myMethod = function() {
return this.each(function(){
doSomething(jQuery(this).attr("id"));
});
function doSomething(id){
//do something
}
function doSomethingElse(){
// some code
}
};
You can view a quick demo here
“我可以移动 myMethod 函数中的所有内容,但它会创建一个 100 行长的函数,人们会因此讨厌我。” ....为什么?
代码必须在某处定义,如果您不希望它可以从外部访问,有几种方法,但我不明白为什么有人会不喜欢您这样做。一切都与范围和您想要的东西有关,只要您不多次声明它并只公开您想要的东西,我看不出有任何问题。
声明它的方式有多种,有些具有相同的效果,我给出的选项只是其中之一,但是将内容放在 myMethod
中是一种非常合理的方法。
为了更完整,here's another alternative :
(function($) {
function doSomething(id){
//do something, e.g: doSomethingElse('bob');
}
function doSomethingElse(str){
//some code
}
$.fn.myMethod = function() {
return this.each(function(){
doSomething(jQuery(this).attr("id"));
});
};
})(jQuery);
或another :
(function($) {
var me = {
doSomething: function(id){
//do something, e.g: this.doSomethingElse('bob');
},
doSomethingElse: function(str){
//some code
}
};
$.fn.myMethod = function() {
return this.each(function(){
me.doSomething(jQuery(this).attr("id"));
});
};
})(jQuery);
相关文章:
关于javascript - 创建一个 jQuery 插件 : best practices regarding functions' visibility?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3014926/