创建 js 小部件时,如何获取小部件的实例?

When creating js widgets, how do I get an instance of my widget?

我正在尝试按照 DevExtreme 的方式实现 widgits。

当他们创建文本框 widgit 时,代码如下:

$("#someContainer").dxTextBox({ options... });

当他们获得 widgit 的实例时,他们会这样做...

$("#someContainer").dxTextBox("instance");

到目前为止,这是我的小部件代码...

(function ($) {
    'use strict';

    $.myWidget = function (element, options) {

        var plugin = this;
        var $base = $(element);

        var defaultOptions = {
            id: null,
        };

        var opts = $.extend({}, defaultOptions, options);

        var me = new function () {
            var self = this;

            var init = {

                widgets: function () {
                    // Do some stuff          
                },

            };

            return {
                init: init,
            };

        };

        me.init.widgets();
    };


    $.fn.myWidget = function (options) {

        return this.each(function () {
            if (undefined === $(this).data('myWidget')) {
                var plugin = new $.myWidget(this, options);
                $(this).data('myWidget', plugin);
            }
        });

    };

})(jQuery)

有了这个我可以创建一个像这样的小部件...

$("#someContainer").myWidget({ id: 1 });

但我希望能够获得小部件的实例,所以我可以这样做:

$("#someContainer").myWidget("instance").showPopup();

还有:

var w = $("#someContainer").myWidget({ options... }).myWidget("instance");
w.showPopup();

如何获取实例?

您必须检测请求实例时的“特殊调用”。这里有一个小例子:

(function ($) {
    'use strict';

    $.myWidget = function (element, options) {

        var plugin = this;
        var $base = $(element);

        var defaultOptions = {
            id: null,
        };

        var opts = $.extend({}, defaultOptions, options);

        var me = new function () {
            var self = this;

            var init = {

                widgets: function () {
                    return {
                      hello: function(){
                        alert("it's me!");
                      }
                    }
                },
                
                

            };

            return {
                init: init,
            };

        };

        return me.init.widgets();
    };


    $.fn.myWidget = function (options) {

        if(options === "instance"){
          return $(this).data('myWidget');
        }

        return this.each(function () {
            if (undefined === $(this).data('myWidget')) {
                var plugin = new $.myWidget(this, options);
                $(this).data('myWidget', plugin);
            }
        });

    };

})(jQuery)


$("#someContainer").myWidget({ id: 1 });

$("#someContainer").myWidget("instance").hello()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="someContainer"></div>