开发者

maintaining state with jquery plugins

I am writing a jQuery plugin that needs to maintain state. There will be multiple instances on a page but each one will have different data associated with keys in a database. I am trying to use the example on the jQuery site as my starting point but have run into some difficulties. Here 'hid' and 'hnid' are the key values I am interested in. In production I will pass them in through options. But my question here is when I click the save button and run the 'save' method, how do I get at my data keys, hid and hnid? Now when I run the code I get a null for data.

(function($) {

    var settings = {        
        'background-color': 'blue'
    };

    var saveData = function() {
        var data = $(this).data('inknote');// now this refers to save button so has no 'data' associated with it.
        console.log('data', data);
    }

var methods = {

    init: function(options) {

        return this.each(function() {

            if (options) {
                $.extend(settings, options);
            }
            var $this = $(this),
            data = $this.data('inknote');

            // If the plugin hasn't been initialized yet
            if (!data) {

                var startData = {
                    target: $this,
                    hid: 1,
      开发者_运维技巧              hnid: 2
                };
                $this.data('inknote', startData);
            }

            var $messageDiv = $('<div>').addClass('messages').html('&nbsp;');
/* am I calling the save method properly here ?*/
                var $saveButton = $('<input>').attr('type', 'button').attr('value', 'Save').bind('click', function() { methods['save'].apply(this); });
                var $printButton = $('<input>').attr('type', 'button').attr('value', 'Print').bind('click', function() { methods['print'].apply(this); });
                var $lockStatus = $('<div>').addClass('lock').addClass('unlocked').html('&nbsp;');
                $this.append($messageDiv).append($saveButton).append($printButton).append($lockStatus);
            });
        },
        save: function(el) {

            return $(this).each(function() {
                saveData(this);                
            });
        },
        print: function(el) {
            return false;
        }
    };

    $.fn.inknote = 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.inknote');
        }

    };

})(jQuery);


I'm not sure what are you trying to achieve exactly, but does this help?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜