jQuery UI 实例 – 部件库(Widget Factory)

jQuery UI Widget Factory(部件工厂)实例

Widget Factory 是 jQuery UI 的核心机制($.widget()),它允许你以标准、模块化的方式创建可重用、可配置、可扩展的状态ful 插件(部件)。所有 jQuery UI 官方组件(如 Dialog、Accordion、Autocomplete 等)都是基于 Widget Factory 构建的。

使用 Widget Factory 创建的插件支持:

  • 选项(options)
  • 方法(methods)
  • 事件回调(callbacks)
  • 私有/公有方法
  • 自动销毁(destroy)
  • 继承与扩展

下面提供几个渐进实例,从基础到高级,帮助你理解并自定义部件。

1. 最基础自定义部件

创建一个简单的“问候”部件。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery UI Widget Factory 基础示例</title>
  <script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="//code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
</head>
<body>
  <div id="greeting" data-name="世界"></div>

  <script>
    // 创建一个名为 "custom.greeting" 的部件
    $.widget("custom.greeting", {
      // 默认选项
      options: {
        name: "陌生人",
        message: "你好"
      },

      // 构造器(初始化时调用)
      _create: function() {
        this.element.text(this.options.message + ", " + this.options.name + "!");
        this._refresh();
      },

      // 私有方法:更新显示
      _refresh: function() {
        this.element.addClass("ui-greeting");
      },

      // 公有方法:更改问候语
      say: function(newMessage) {
        this.option("message", newMessage);
        this._create();  // 重新渲染
      },

      // 销毁时清理
      _destroy: function() {
        this.element.removeClass("ui-greeting").text("");
      }
    });

    // 使用部件
    $(function() {
      $("#greeting").greeting({
        name: $("#greeting").data("name"),  // 从 data 属性读取
        message: "欢迎"
      });

      // 3秒后调用公有方法
      setTimeout(function() {
        $("#greeting").greeting("say", "再见");
      }, 3000);
    });
  </script>
</body>
</html>

2. 带事件回调的计数器部件

支持点击增加计数,并触发自定义事件。

<div id="counter"></div>
<button id="inc">+1</button>

<script>
  $.widget("custom.counter", {
    options: {
      value: 0,
      step: 1,
      change: null  // 回调事件
    },

    _create: function() {
      this.element.text(this.options.value).addClass("ui-counter");
      this._on(this.element, { click: this.increment });
    },

    increment: function() {
      this.option("value", this.options.value + this.options.step);
      this._trigger("change", null, { value: this.options.value });  // 触发事件
    },

    // 公有方法:获取/设置值
    value: function(newValue) {
      if (newValue === undefined) {
        return this.options.value;
      }
      this.option("value", newValue);
      this.element.text(newValue);
    }
  });

  $(function() {
    $("#counter").counter({
      change: function(event, data) {
        console.log("计数变为:" + data.value);
      }
    });

    $("#inc").click(function() {
      $("#counter").counter("increment");
    });
  });
</script>

3. 继承现有部件(扩展 Dialog)

创建一个带默认标题和按钮的“确认对话框”。

<button id="openConfirm">打开确认框</button>

<script>
  // 继承 $.ui.dialog
  $.widget("custom.confirmDialog", $.ui.dialog, {
    options: {
      title: "确认操作",
      modal: true,
      buttons: {
        "确定": function() {
          $(this).confirmDialog("close");
          alert("已确认!");
        },
        "取消": function() {
          $(this).confirmDialog("close");
        }
      }
    }
  });

  $(function() {
    $("#openConfirm").click(function() {
      $("<div>你确定要执行此操作吗?</div>").confirmDialog("open");
    });
  });
</script>

4. 完整工具提示部件(类似 Tooltip)

自定义一个简单 Tooltip。

<span class="has-tip" title="这是一个自定义提示">悬停我</span>

<script>
  $.widget("custom.myTooltip", {
    options: {
      content: ""
    },

    _create: function() {
      this.tooltip = $("<div>")
        .addClass("ui-mytooltip")
        .text(this.element.attr("title"))
        .hide()
        .appendTo("body");

      this._on(this.element, {
        mouseenter: this._show,
        mouseleave: this._hide
      });

      this.element.removeAttr("title");
    },

    _show: function() {
      this.tooltip.show().position({
        my: "left center",
        at: "right+10 center",
        of: this.element
      });
    },

    _hide: function() {
      this.tooltip.hide();
    },

    destroy: function() {
      this.tooltip.remove();
      $.Widget.prototype.destroy.call(this);
    }
  });

  $(function() {
    $(".has-tip").myTooltip();
  });
</script>

<style>
  .ui-mytooltip { background: #333; color: white; padding: 8px; border-radius: 4px; }
</style>

Widget Factory 核心方法总结

  • _create():初始化
  • _init():每次调用无参数方法时(如 .widget()
  • _setOption(key, value):选项改变时自动调用,可重写
  • _trigger(type, event, data):触发事件
  • option():获取/设置选项
  • _on() / _off():事件绑定(自动清理)

使用 Widget Factory 创建的插件命名空间推荐格式:namespace.widgetName(如 ui.dialogcustom.progressLoader

如果你想看一个进度加载器部件可拖拽面板、或基于现有组件的复杂扩展,请告诉我具体需求!

文章已创建 3350

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部