user1354743 user1354743 - 11 months ago 60
jQuery Question

Call a jQuery plugin function outside the Plugin

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.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.findWinner(column, i);


main.js I have tried:


Maybe someone has a clue! Thx in advance!

Answer Source

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.

  1. 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();

    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.

  2. Use a different plugin pattern. Personally I like the jQueryUI widget factory approach, but you will have to include jQueryUI for it. Docs