如何在jQuery插件实例之间共享属性和函数?
问题描述:
我想分享一个jQuery插件实例(我创建一个)之间的属性和方法 我会如何做到这一点?如何在jQuery插件实例之间共享属性和函数?
Supose我有一个简单的插件定义为:
// add the plugin to the jQuery.fn object
$.fn.clickableImage = function(options) {
this.set_not_clicked = function(){
return this.each(function() {
$(this).addClass('not-clicked');
});
};
// iterate through the DOM elements we are attaching the plugin to
return this.each(function() {
$(this).click(function(){
parent.set_not_clicked() //how to get "parent" ???
$(this).removeClass('not-clicked').addClass('clicked');
});
});
}
而且,图像实例化如下:
$(function(){
$('#some-selector img').clickableImage();
});
如何使 “clickableImage” 知道他人的 “clickableImage”?
答
闭包是javascript中的常见模式,因为它们可以防止全局名称空间污染。
详见该SO问题:What exactly does "closure" refer to in JavaScript?
A“闭合”是可以与结合这些变量的环境具有自由变量一起(即“封闭的”表达的表达(通常是功能) )。
你的情况,这将是这样的:
(function($){
var instances = [];
function count(){
alert(instances.length);
}
function hide_parent(){
for(var i=0;i<instances.length;i++){
$(instances[i]).parent().hide();
}
}
$.fn.clickableImage = function(options) {
// Use a class to prevent double bindings.
this
.filter(':not(.clickImage)')
.addClass('clickImage')
// iterate through the DOM elements we are attaching the plugin to
.each(function() {
instances.push(this);
$(this).click(function(){
// Alert the current image count:
count();
// Hide all parents:
hide_parent();
})
})
return this;
}
}(jQuery));
alert(typeof instances);// will return undefined
你也可以添加一个类,并在DOM中搜索类:
$.fn.clickableImage = function(options) {
// iterate through the DOM elements we are attaching the plugin to
return this
.addClass('clickImage')
.each(function() {
$(this).click(function(){
$("img.clickImage").each(function(){
$(this).parent().hide();
});
alert(instances_count);
});
});
}
你的答案是十分正确的...也许我简化了太多我的例子,因为我想做一些更复杂的事情比提醒实例的数量...我会编辑我的问题 – 2012-08-11 20:56:49
看到我更新的答案。它允许做任何你喜欢的共享实例:) – jantimon 2012-08-11 21:05:25
@DiegoDorado我添加了你的“隐藏所有父母”的例子。 – jantimon 2012-08-11 21:09:25