开发者

jQuery .data() and plugins

开发者 https://www.devze.com 2023-04-03 18:31 出处:网络
I am trying to use jQuery\'s .data() tool in a jQuery plugin but I\'m getting some odd results. Here is a cut down version of my plugin with the relevant code:

I am trying to use jQuery's .data() tool in a jQuery plugin but I'm getting some odd results. Here is a cut down version of my plugin with the relevant code:

(function( $ ){ 

    var methods = {
        init : function( options ) { 

            // Do some stuff
            this.data('name', 'New Component');
            return this;
        },
        getStateData : function () {
            // Function returns all data for save
            var state = new Object;

            state.name =  this.data('name');

            // snip ... Add some other bits to state
            // ...

            return state;               
        },
        setStateData: function (args) {
            var key     = args[0];
            var value   = args[1];

            // snip
            this.data(key, value);
        }
    };

    $.fn.component7Segment = 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.designComponent' );
        }       
    };
})( jQuery );

If I call $(instance-of-plugi开发者_运维技巧n).component7Segment('getStateData'); the plugin returns the correct 'name' however if I call setStateData to change the name it has not changed the 'name' value when I next call getStateData.

Doing console.log(this); in each function looks slightly different so I started trying:

$.data($('#object-id'), 'name', value);

This still doesn't have the desired effect.

Can anybody see what I am missing?


Assuming you're calling setStateData like this:

$(instance).component7Segment("setStateData", "name", "Foo");

the setStateData function should be changed to look like this:

setStateData: function () {
    var key     = arguments[0];
    var value   = arguments[1];

    // snip
    this.data(key, value);
}

Note the removal of the args parameter and the use of the special arguments array-like object instead.

Example: http://jsfiddle.net/andrewwhitaker/ShFHC/

Your original problem was most likely that you were calling setStateData with parameters name and "foo". args[0] and args[1] was actually accessing the characters in name at that position instead of the arguments passed to the function.

0

精彩评论

暂无评论...
验证码 换一张
取 消