3

请针对以下提到的场景提出解决方案

背景(jQuery插件):

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

和可变动作看起来像:

var actions = {
    init: function (options) {
        if (this.length) {
            var settings = $.extend({}, $.fn.myplugin.defaults);
            return this.each(function () {
                if (options) {
                    settings = $.extend(settings, options);
                }

                $(this).data('myplugin', new MyPlugin($(this), settings));
            });
        } else {
            throw new Error('unable to init undefined');
        }
    },
    update: function () {
        ...
    },
    destroy: function () {
        ...
    }
};

MyPlugin看起来像

function MyPlugin($el, settings) {
    var $content = $('.content', $el);

    var a = function setup() { ... };

    var b = function hold() { ... }

    $content.on({
        'click': function(e) { ... },
        'hover': function(e) { ... }
    });
}

我知道我可以将 $.cache 转储到控制台并查看 .data() 中关联的内容。

想要的问题/建议:

如果我像这样调用更新函数,$('myEle').myplugin('update')我需要update function更改使用.data()API 创建和缓存的 MyPlugin 实例的状态。有哪些可能的方法来做到这一点?

我目前的结果$('myEle').data('myplugin')显示MyPlugin{}在花括号之间没有任何内容。

4

1 回答 1

1

The problem doesn't have anything to do with jQuery or the data() API, it's due to a misunderstanding about functions, objects and constructors in JavaScript.

This is easy to test inside the JavaScript console in a browser:

> function MyPlugin() { var a = 1; var b = 2; }
undefined
> new MyPlugin()
MyPlugin {}

> function MyPlugin() { this.a = 1; this.b = 2; }
undefined
> new MyPlugin()
MyPlugin {a: 1, b: 2}
于 2013-04-17T19:54:25.883 回答