如何扩展现有的 jQuery UI 小部件? [英] How to extend an existing jQuery UI widget?

查看:31
本文介绍了如何扩展现有的 jQuery UI 小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 jQuery v1.8.3 和 jQuery UI v1.9.2.我想通过添加和覆盖来扩展现有的 jQuery UI 小部件(在我的例子中是 Autocomplete 小部件)一些选项和方法,但保留其他功能与正式版本中的功能相同.我怎样才能使它成为正确"(也许是标准")的方式?

I am using jQuery v1.8.3 and jQuery UI v1.9.2. I would like to extend an existing jQuery UI widget (in my case the Autocomplete widget) by adding and overriding just some options and methods but keeping the others functionalities as those present in the official release. How can I make that the "proper" (maybe, the "standard") way?

PS:我在网上搜索(12, ...) 我发现文档主要与创建一个新的 jQuery有关UI 小部件,但不扩展现有的小部件.

P.S.: I searched on the Web (1, 2, ...) and I found documentation mostly related to creating a new jQuery UI widget but not to extending an existing one.

推荐答案

在 jQuery UI 1.9+ 中,扩展小部件的方式与创建新小部件的方式相同.小部件工厂 ($.widget()) 支持以下几种情况:

In jQuery UI 1.9+, extending a widget is done in the same manner as creating a new widget. The widget factory ($.widget()) supports a few scenarios:

使用基础小部件 ($.Widget) 作为起点创建一个新小部件:

Creating a new widget using the base widget ($.Widget) as the starting point:

$.widget( "ns.widget", { ... } )

创建一个继承现有小部件的新小部件:

Creating a new widget that inherits from an existing widget:

$.widget( "ns.widget", $.ns.existingWidget, { ... } )

扩展小部件:

$.widget( "ns.widget", $.ns.widget, { ... } )

您会注意到扩展语法和继承语法是相同的.小部件工厂足够聪明,可以注意到您正在创建的小部件和您从其继承的小部件是相同的,并对其进行了适当的处理.

You'll notice that the extending syntax and the inheritance syntax are the same. The widget factory is smart enough to notice that the widget you're creating and the widget you're inheriting from are the same and handle it appropriately.

在继承或扩展小部件时,您只需定义要更改或添加的内容.基础小部件上还有一些新方法,可以更轻松地使用继承和更改上下文的方法.阅读 jQuery.Widget 文档,获取方法及其描述的完整列表.如果您要扩展,您肯定想阅读 _super()一个小部件.

When inheriting or extending a widget, you only need to define what you want to change or add. There are also a few new methods that exist on the base widget to make it easier to work with inheritance and methods that change context. Read the jQuery.Widget documentation for a full list of methods and their descriptions. You'll definitely want to read about _super() if you're extending a widget.

以下示例将默认 delay 选项更改为 500 并添加一个新选项 prefix,该选项已添加到所有建议中:

Here's an example that would change the default delay option to 500 and add a new option prefix which is added to all suggestions:

$.widget( "ui.autocomplete", $.ui.autocomplete, {
    options: {
        delay: 500,
        prefix: ""
    },

    _renderItem: function( ul, item ) {
        var label = item.label;
        if ( this.options.prefix ) {
            label = this.options.prefix + " " + label;
        }
        return $( "<li>" )
            .append( $( "<a>" ).text( label ) )
            .appendTo( ul );
    },
});

这篇关于如何扩展现有的 jQuery UI 小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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