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

在离线 Chromium 中运行 Widget Factory 状态隔离、选项更新与销毁实验

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

HTML = """<!doctype html>
<html>
<head><meta charset="utf-8"><title>Widget Factory Lab</title></head>
<body>
<div id="c1"></div>
<div id="c2"></div>
<script>
// Minimal faithful offline jQuery + Widget Factory core
(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] : Array.isArray(sel) ? 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; },
    addClass(cls) { return this.each(function() { this.classList.add(...cls.split(/\\s+/).filter(Boolean)); }); },
    removeClass(cls) { return this.each(function() { this.classList.remove(...cls.split(/\\s+/).filter(Boolean)); }); },
    hasClass(cls) { return this.els[0] ? this.els[0].classList.contains(cls) : false; },
    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 = function(target, ...sources) {
    const out = target || {};
    for (const src of sources) {
      if (!src) continue;
      for (const k of Object.keys(src)) out[k] = src[k];
    }
    return out;
  };
  $.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, value) {
      if (key === undefined) return $.extend({}, this.options);
      if (typeof key === "string") {
        if (value === undefined) return this.options[key];
        this._setOption(key, value);
      } else {
        for (const k of Object.keys(key)) this._setOption(k, key[k]);
      }
      return this;
    },
    _setOption(key, value) {
      this.options[key] = value;
      return this;
    },
    destroy() {
      this._destroy();
      this.element.removeData(this.widgetFullName);
    },
    _destroy() {}
  };
  $.widget = function(name, prototype) {
    const parts = name.split(".");
    const namespace = parts[0], widgetName = parts[1];
    const fullName = namespace + "-" + widgetName;
    $[namespace] = $[namespace] || {};
    function Ctor(options, element) {
      if (!(this instanceof Ctor)) return new Ctor(options, element);
      if (arguments.length) this._createWidget(options, element);
    }
    Ctor.prototype = Object.assign(Object.create($.Widget.prototype), {
      constructor: Ctor,
      widgetName,
      namespace,
      widgetFullName: fullName,
      options: $.extend({}, prototype.options)
    }, prototype);
    $[namespace][widgetName] = Ctor;
    $.fn[widgetName] = function(options, ...args) {
      if (typeof options === "string") {
        let returnValue = this;
        this.each(function() {
          const inst = $(this).data(fullName);
          if (!inst) throw new Error("cannot call methods on " + widgetName + " prior to initialization");
          if (typeof inst[options] !== "function" || options.startsWith("_")) {
            throw new Error("no such method '" + options + "'");
          }
          const res = inst[options](...args);
          if (res !== inst && res !== undefined) returnValue = res;
        });
        return returnValue;
      }
      return this.each(function() {
        const inst = $(this).data(fullName);
        if (inst) { inst.option(options || {}); }
        else { new Ctor(options, this); }
      });
    };
  };
  global.$ = global.jQuery = $;
})(window);

$.widget("custom.counter", {
  options: { value: 0, step: 1 },
  _create() {
    this.element.addClass("custom-counter").text(this.options.value);
  },
  increment(delta) {
    const inc = delta !== undefined ? delta : this.options.step;
    this.options.value += inc;
    this.element.text(this.options.value);
  },
  value() {
    return this.options.value;
  },
  _destroy() {
    this.element.removeClass("custom-counter").text("");
  }
});
</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("""() => {
                $("#c1").counter({ value: 10 });
                $("#c2").counter({ value: 50 });
                return {
                    c1Text: $("#c1").text(),
                    c2Text: $("#c2").text(),
                    c1Class: $("#c1").hasClass("custom-counter"),
                    isolated: $("#c1").data("custom-counter") !== $("#c2").data("custom-counter")
                };
            }""")
            exp1 = {"c1Text": "10", "c2Text": "50", "c1Class": True, "isolated": True}
            cases.append(dict(
                name="widget_factory_stateful_lifecycle",
                expected=exp1,
                actual=r1,
                passed=(r1 == exp1),
            ))

            r2 = page.evaluate("""() => {
                $("#c1").counter("increment", 5);
                const afterInc = $("#c1").counter("value");
                $("#c1").counter("option", "step", 2);
                $("#c1").counter("increment");
                return {
                    afterInc,
                    finalVal: $("#c1").counter("value"),
                    finalText: $("#c1").text(),
                    c2Unchanged: $("#c2").counter("value")
                };
            }""")
            exp2 = {"afterInc": 15, "finalVal": 17, "finalText": "17", "c2Unchanged": 50}
            cases.append(dict(
                name="widget_factory_method_and_option",
                expected=exp2,
                actual=r2,
                passed=(r2 == exp2),
            ))

            r3 = page.evaluate("""() => {
                $("#c1").counter("destroy");
                return {
                    c1HasClass: $("#c1").hasClass("custom-counter"),
                    c1Text: $("#c1").text(),
                    c1InstanceRemoved: $("#c1").data("custom-counter") === undefined,
                    c2StillActive: $("#c2").counter("value") === 50
                };
            }""")
            exp3 = {
                "c1HasClass": False,
                "c1Text": "",
                "c1InstanceRemoved": True,
                "c2StillActive": True,
            }
            cases.append(dict(
                name="widget_factory_destroy_cleanup",
                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-lab/explore-widget-factory.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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