I have built a jQuery Plugin, but now I need to use one function from the Plugin outside of the Plugin.
The Plugin
(function ($) {
jQuery.fn.vierGewinnt = function () {
var VierGewinnt = function (config) {
this.view = config.view;
this.dx;
this.turn = 1;
}
VierGewinnt.prototype.setToken = function (column) {
for (var i = this.rows; i > 0; i--) {
if (this.gamearray[column][i] == 0) {
this.gamearray[column][i] = "red";
this.turn++;
this.findWinner(column, i);
break;
}
}
}})(jQuery);
main.js I have tried:
$.setToken()
$.fn.vierGewinnt.setToken()
$.fn.vierGewinnt.VierGewinnt.setToken()
Maybe someone has a clue! Thx in advance!
All you need to do is return the function/plugin closure and create any methods you want to control outside the plugin as a property of the closure ($this).
$.fn.vierGewinnt = function(options) {
var $this = this;
$this.setToken = function() {
// setting token
};
return $this;
};
And then save the reference to the plugin to call the method later.
var vierPlugin = $('.some-element').vierGewinnt();
vierPlugin.setToken(); // setting token outside plugin
The way you have done it, you can't call it from outside.
There are a few patterns how you can make js/jquery widgets.
You are trying to combine the "normal" prototype with jQuery.
As I see you have two options.
Wrap you jQuery method to return the instance of the constructor. You can call prototype methods on it. Something like:
$.fn.vierGewinnt = function(config){
return new VierGewinnt (config);
};
Then you can instance the plugin and call the method
var plugin = $('#someSelector').vierGewinnt();
plugin.setToken(column);
In this case almost all your code can go outside the (function ($) block. You are just using jQuery as a wrapper, everything else is just ordinary javascript. As far as I can see your plugin is not called on any DOM element. It that case I don't see a lot sense in a jQuery plugin... it is pure javascript. If that is the case, just loose all the jQuery stuff from your example, and it will work.
Use a different plugin pattern. Personally I like the jQueryUI widget factory approach, but you will have to include jQueryUI for it. Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With