Gus
Gus

Reputation: 943

Jquery - reserve element of the plugin

I'm trying to do a simple plugin that uses some functions outside of the this.each method I would like to use on two elements of the same page but I have problems because it makes reference to the same table elements.

;(function ($, window, document, undefined) {
    'use strict';

    function init() {
        makeHeader.call(this);
        $('<p>footer</p>').insertAfter('table');
    }

    function makeHeader() {
        $('<p>header</p>').insertBefore('table');
    }

    $.fn.MYPlugin = function(options) {
        var options = $.extend(true, {}, defaults, options);

        return this.each(function() {
            var $this = $(this);

            init.call(this);

            $this.on('click', 'th', function() {
                alert('Hallo!');
            });

        });
    };
})(jQuery, window, document);

js

$(function() {
    $('#tbl').MYPlugin();
    $('#tbl2').MYPlugin();
});

html

<table id="tbl" class="table table-condensed table-hover table-striped table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Code</th>
            <th>Name</th>
            <th>Phone</th>
        </tr>
    </thead>
</table>

<table id="tbl2" class="table table-condensed table-hover table-striped table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Code</th>
            <th>Name</th>
            <th>Phone</th>
        </tr>
    </thead>
</table>

How can I do so that the plugin only works in the reserved context of the initialized element (#tbl or #tbl2) so you can use it on multiple items on the same page? Thanks

Upvotes: 0

Views: 114

Answers (1)

Roamer-1888
Roamer-1888

Reputation: 19288

You take the trouble to intialize by calling init.call(this) but fail to utilize this in init() other than passing it on to makeHeader() ... where it is also not utilized!

Try :

function init() {
    makeHeader.call(this);
    $('<p>footer</p>').insertAfter(this);
}

function makeHeader() {
    $('<p>header</p>').insertBefore(this);
}

Upvotes: 1

Related Questions