एक और तरीका है इस स्थिति है, जो उपयोगी है जब आप कहीं और से (शायद एक अलग फ़ाइल आदि) अपने प्लगइन के तरीकों कॉल करना चाहते हैं संभाल करने के लिए एक वर्ग के रूप प्लगइन तर्क लिखने के लिए और फिर उस वर्ग के अंदर का दृष्टांत है jQuery प्लगइन, $.data
में उदाहरण संग्रहित।
(function($) {
var Animal = function(el, settings) {
this.$el = $(el);
this.settings = settings;
this.foo();
};
Animal.prototype.eat = function() {
// Do stuff
if (this.settings.isVegetarian) {
console.log('I eat plants');
} else {
console.log('I eat meat');
}
};
Animal.prototype.play = function() {
// Do other stuff but return this.$el so you can maintain chain
return this.$el;
};
// Create jQuery plugin
var pluginName = 'myPlugin';
$.fn[pluginName] = function(options) {
// Defaults
var settings = $.extend({
isVegetarian: true,
}, options);
return this.each(function() {
if (!$.data(this, pluginName)) {
// Store plugin instace with element (this),
// so public methods can be called later:
// $('.el').data('myPlugin').eat();
$.data(this, pluginName, new Animal(this, settings));
}
});
};
}(jQuery));
तब जब आप अपने प्लगइन कॉल करना चाहते हैं, यह सिर्फ सामान्य की तरह है:
$('.dog).myPlugin();
और एक विधि कॉल:
$('.dog').data('myPlugin').eat();
THX, सरल और स्पष्ट – apelliciari