继承jQuery小部件并从外部调用一些基本小部件的方法 [英] Inherit jQuery widgets and call some base widget's method from outside

查看:126
本文介绍了继承jQuery小部件并从外部调用一些基本小部件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个jQuery小部件,小部件A是基础部件,小部件B继承了小部件A.

I have two jQuery widgets, Widget A is the base one and the Widget B inherits Widget A.

小部件A:

$(function () {
    $.widget("custom.widgetA", {

        _create: function () {
            this.element
                .addClass('ui-widget-a')
                .append(
                    $(document.createElement('div')).text('Widget A')
                );
        },

        someMethod: function() {
            return 'widget A';
        }
    });

}(jQuery));

小部件B:

$(function () {
    $.widget("custom.widgetB", $.custom.widgetA, {

        _create: function () {
            this.element
                .addClass('ui-widget-b')
                .append(
                    $(document.createElement('div')).text('Widget B')
                );

            this._super();
        },

        someOtherMethod: function() {
            return 'widget B';
        }
    });

}(jQuery));

比我将Widget B应用于某些HTML元素

than I apply Widget B to some HTML element

$('#widgetB').widgetB();

现在我要从小部件A调用方法someMethod ...为此,我使用此代码

and now I want to call method someMethod from widget A... in order to do this I use this code

$('#widgetB').widgetA('someMethod')

但收到错误消息

在初始化之前不能在widgetA上调用方法;尝试做 调用方法"someMethod"

cannot call methods on widgetA prior to initialization; attempted to call method 'someMethod'

我知道我是否可以这样称呼它

I know if I call it this way it will work

$('#widgetB').widgetB('someMethod')

但是我需要使用基本窗口小部件来调用它...可以吗?

but I need to call it using the base widget... is possible to do?

这是小提琴和我的示例

更新

以这种方式发生的原因这里

the reason why it happens this way here

推荐答案

没有什么能阻止您init在同一个元素上同时放置两个小部件:

There's really nothing stopping you from initing both widgets on the same element:

$.widget("custom.widgetB", $.custom.widgetA, {

    _create: function () {
        this._super();
        $(this.element).widgetA(this.options);
    }
});

现在您可以同时调用两者:

Now you can call both:

$('#widgetB').widgetA('someMethod');
$('#widgetB').widgetB('someMethod');

在您的情况下,create函数实际上会创建新元素(具有jQuery速记$("<div>")),因此您只需要为widgetA包括上述init ializer之一即可. this._super()$(this.element).widgetA()

In your case the create function actually creates new elements (which has a jQuery shorthand $("<div>")), so you'd have to only include one of the above initializers for widgetA ie. only one of this._super() or $(this.element).widgetA()

提琴更新

如果要在widgetA实例上存储非原始对象,这可能会导致一些额外的复杂性,但是对于这种模型,您可能不应该一开始就这样做

This can lead to some additional complexity if you're storing non-primitive objects on the widgetA instance, but with this model you probably shouldn't be doing that in the first place

这篇关于继承jQuery小部件并从外部调用一些基本小部件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆