蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在离线 Chromium 中对比无状态 $.fn、手工 defaults 合并与 Widget Factory 自动选项管理

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-widget-factory-why.py
explore-widget-factory-why.py225 行
"""Offline Chromium lab for jQuery UI Ch14: Why Use the Widget Factory."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head><meta charset="utf-8"><title>Why Widget Factory Lab</title></head>
<body>
<div id="stateless">init</div>
<div id="manual1"></div>
<div id="manual2"></div>
<div id="wf1"></div>
<script>
(function(global) {
  const dataStore = new WeakMap();
  function getDataMap(el) {
    if (!dataStore.has(el)) dataStore.set(el, {});
    return dataStore.get(el);
  }
  function $(sel) {
    if (sel && sel._isJQ) return sel;
    const els = typeof sel === "string"
      ? Array.from(document.querySelectorAll(sel))
      : (sel instanceof Element ? [sel] : []);
    return Object.assign(Object.create($.fn), { _isJQ: true, length: els.length, els });
  }
  $.fn = {
    each(fn) { this.els.forEach((el, i) => fn.call(el, i, el)); return this; },
    text(val) {
      if (val === undefined) return this.els[0] ? this.els[0].textContent : "";
      return this.each(function() { this.textContent = String(val); });
    },
    data(key, val) {
      if (!this.els[0]) return undefined;
      const map = getDataMap(this.els[0]);
      if (val === undefined) return map[key];
      map[key] = val;
      return this;
    },
    removeData(key) { return this.each(function() { delete getDataMap(this)[key]; }); }
  };
  $.extend = (target, ...sources) => Object.assign(target || {}, ...sources);

  // Stateless plugin extending $.fn (jQuery.prototype)
  $.fn.setGreeting = function(msg) {
    this.text(msg);
    return this;
  };

  // Manual defaults pattern
  $.fn.legacyPlugin = function(options) {
    const merged = $.extend({}, $.fn.legacyPlugin.defaults, options);
    return this.each(function() {
      this.dataset.merged = JSON.stringify(merged);
    });
  };
  $.fn.legacyPlugin.defaults = { param1: "foo", param2: "bar", param3: "baz" };

  // Widget Factory
  $.Widget = function() {};
  $.Widget.prototype = {
    _createWidget(options, element) {
      this.element = $(element);
      this.options = $.extend({}, this.options, options);
      this.element.data(this.widgetFullName, this);
      this._create();
    },
    _create() {},
    option(key, val) {
      if (key === undefined) return $.extend({}, this.options);
      if (typeof key === "string") {
        if (val === undefined) return this.options[key];
        this.options[key] = val;
      } else {
        $.extend(this.options, key);
      }
      return this;
    },
    _trigger(type, data) {
      const cb = this.options[type];
      if (typeof cb === "function") cb.call(this.element.els[0], { type: this.widgetName + type }, data);
    },
    destroy() {
      this._destroy();
      this.element.removeData(this.widgetFullName);
    },
    _destroy() {}
  };
  $.widget = function(name, proto) {
    const [ns, wname] = name.split(".");
    const full = ns + "-" + wname;
    $[ns] = $[ns] || {};
    function Ctor(options, element) { this._createWidget(options, element); }
    Ctor.prototype = Object.assign(Object.create($.Widget.prototype), {
      constructor: Ctor, widgetName: wname, widgetFullName: full,
      options: $.extend({}, proto.options)
    }, proto);
    $[ns][wname] = Ctor;
    $.fn[wname] = function(options, ...args) {
      if (typeof options === "string") {
        let ret = this;
        this.each(function() {
          const inst = $(this).data(full);
          const r = inst[options](...args);
          if (r !== inst && r !== undefined) ret = r;
        });
        return ret;
      }
      return this.each(function() {
        const inst = $(this).data(full);
        if (inst) inst.option(options || {});
        else new Ctor(options, this);
      });
    };
  };
  global.$ = global.jQuery = $;
})(window);

$.widget("ns.plugin", {
  options: { param1: "foo", param2: "bar", param3: "baz" },
  _create() {
    this.updates = 0;
    this.element.text(this.options.param1 + "|" + this.options.param2 + "|" + this.options.param3);
  },
  applyChange(newVal) {
    this.updates += 1;
    this.options.param2 = newVal;
    this.element.text(this.options.param1 + "|" + this.options.param2 + "|" + this.options.param3);
    this._trigger("changed", { updates: this.updates, param2: newVal });
  },
  updateCount() { return this.updates; },
  _destroy() { this.element.text("destroyed"); }
});
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            page.set_content(HTML)

            r1 = page.evaluate("""() => {
                const el = $("#stateless");
                const ret = el.setGreeting("hello");
                return {
                    chainedSelf: ret === el,
                    textAfterFirst: el.text(),
                    textAfterRepeat: el.setGreeting("hello").text(),
                    hasStoredState: el.data("stateless") !== undefined
                };
            }""")
            exp1 = {
                "chainedSelf": True,
                "textAfterFirst": "hello",
                "textAfterRepeat": "hello",
                "hasStoredState": False,
            }
            cases.append(dict(name="stateless_fn_plugin_vs_stateful", expected=exp1, actual=r1, passed=(r1 == exp1)))

            r2 = page.evaluate("""() => {
                $("#manual1").legacyPlugin({ param2: "custom" });
                const first = JSON.parse(document.getElementById("manual1").dataset.merged);
                const defaultsUnmutated = $.fn.legacyPlugin.defaults.param2 === "bar";
                $.fn.legacyPlugin.defaults.param1 = "global";
                $("#manual2").legacyPlugin({ param3: "override" });
                const second = JSON.parse(document.getElementById("manual2").dataset.merged);
                return { first, defaultsUnmutated, second };
            }""")
            exp2 = {
                "first": {"param1": "foo", "param2": "custom", "param3": "baz"},
                "defaultsUnmutated": True,
                "second": {"param1": "global", "param2": "bar", "param3": "override"},
            }
            cases.append(dict(name="manual_fn_defaults_merge", expected=exp2, actual=r2, passed=(r2 == exp2)))

            r3 = page.evaluate("""() => {
                const events = [];
                const el = $("#wf1").plugin({
                    param2: "init-bar",
                    changed(evt, data) { events.push(evt.type + ":" + data.updates + ":" + data.param2); }
                });
                const initialText = el.text();
                el.plugin("applyChange", "next-bar");
                const updates = el.plugin("updateCount");
                const p3 = el.plugin("option", "param3");
                el.plugin("destroy");
                return {
                    initialText,
                    updates,
                    param3: p3,
                    events,
                    afterDestroyText: el.text(),
                    instanceCleared: el.data("ns-plugin") === undefined
                };
            }""")
            exp3 = {
                "initialText": "foo|init-bar|baz",
                "updates": 1,
                "param3": "baz",
                "events": ["pluginchanged:1:next-bar"],
                "afterDestroyText": "destroyed",
                "instanceCleared": True,
            }
            cases.append(dict(name="widget_factory_consistent_api_and_defaults", expected=exp3, actual=r3, passed=(r3 == exp3)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jqueryui-widget-factory-why-lab/explore-widget-factory-why.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-widget-factory-why.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a957.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习