Richard
Richard

Reputation: 23

Passing jQuery element data between methods?

I'm trying to create my first jQuery plugin, reading jQuery plugin authoring and one of the things it really emphasizes is to use methods instead of namespaces. I'm also trying to use the data from that guide to bounce variables between methods but it's not working. I need to create some data, pass it to another method to update it and send it somewhere else.

(function($) {

    var methods = {
        init : function(settings) {

            return this.each(function(){

                var x = 3; 
                var object = $(this);

                // Bind variables to object
                $.data(object, 'x', x);

                $(object).bbslider('infoParse');

                var y = $.data(object,'y');
                alert(y);

            }); // End object loop

        }, // End init
        infoParse : function() { 
            var object = $(this);
            var x = $.data(object,'x');

            alert(x);

            var y = 10;
            $.data(object,'y',y);
        }, // End infoParse
    }; // End method


    $.fn.bbslider = 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.bbslider' );
        }       
    }; // End slider

})(jQuery); 

Here's a jsFiddle to show what I mean: http://jsfiddle.net/wRxsX/3/

How do I pass variables between methods?

Upvotes: 2

Views: 247

Answers (1)

farmer1992
farmer1992

Reputation: 8156

see if this http://jsfiddle.net/wRxsX/6/ is ok ?

element.data(k,v)

$.data should use on element

http://api.jquery.com/data/

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

Upvotes: 2

Related Questions