6

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

1 Answer 1

6

You need to use

        methods.otherFunction.apply(this);

instead of

        methods.otherFunction();

to make the scopes correct.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.