Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing jQuery plugin data

The jQuery documentation suggests storing additional info per DOMElement using data(). But I'm having a hard time accessing the saved data in a good way.

The scope changes when I call other functions which makes me lose my way :)

(function ($) {
    var methods = {
        init: function (options) {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data('myPlugin');

                if (!data) {
                    $(this).data('myPlugin', {
                        testValue: true
                    });

                    data = $this.data('myPlugin');
                }
            });
        },

        testFunction: function () {
            console.log('t: '+$(this).data('myPlugin').testValue);
            methods.otherFunction();
        },

        otherFunction: function () {
            console.log('o: '+$(this).data('myPlugin').testValue);
        }
    };

    $.fn.myPlugin = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.myPlugin');
        }
    };

})(jQuery);

$(document).ready(function () {
    $('body').myPlugin();
    $('body').myPlugin('testFunction');
});

Console output:

t: true
Uncaught TypeError: Cannot read property 'testValue' of undefined
like image 549
Per Salbark Avatar asked Aug 04 '11 10:08

Per Salbark


1 Answers

You need to use

        methods.otherFunction.apply(this);

instead of

        methods.otherFunction();

to make the scopes correct.

Demo: http://jsfiddle.net/ayNUD/

like image 174
Dogbert Avatar answered Sep 24 '22 14:09

Dogbert