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

在离线 Chromium 中对比插件调用、实例调用、instance() 与链式返回边界

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-widget-method.py
explore-widget-method.py205 行
"""Offline Chromium lab for jQuery UI Ch13: Widget Method Invocation."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head><meta charset="utf-8"><title>Widget Method Lab</title></head>
<body>
<div class="selector" id="dlg1">Dialog 1</div>
<div class="selector" id="dlg2">Dialog 2</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; },
    css(prop, val) {
      if (val === undefined) return this.els[0] ? getComputedStyle(this.els[0])[prop] : "";
      return this.each(function() { this.style[prop] = 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;
    }
  };
  $.extend = (t, ...ss) => Object.assign(t || {}, ...ss);
  $.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() {},
    instance() { return this; },
    option(key, val) {
      if (val === undefined) return this.options[key];
      this.options[key] = val;
      return this;
    }
  };
  $.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 returnValue = this;
        let hasReturn = false;
        this.each(function() {
          const inst = $(this).data(full);
          if (options === "instance") {
            returnValue = inst;
            hasReturn = true;
            return;
          }
          if (!inst) throw new Error("not initialized");
          const res = inst[options](...args);
          if (!hasReturn && res !== inst && res !== undefined) {
            returnValue = res;
            hasReturn = true;
          }
        });
        return returnValue;
      }
      return this.each(function() {
        const inst = $(this).data(full);
        if (!inst) new Ctor(options, this);
      });
    };
  };
  global.$ = global.jQuery = $;
})(window);

$.widget("ui.dialog", {
  options: { height: 320, autoOpen: true },
  _create() {
    this._open = !!this.options.autoOpen;
    this.element.css("display", this._open ? "block" : "none");
  },
  open() {
    this._open = true;
    this.element.css("display", "block");
  },
  close() {
    this._open = false;
    this.element.css("display", "none");
  },
  isOpen() {
    return this._open;
  }
});
</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 dlg = $("#dlg1").dialog({ height: 320 });
                const h = dlg.dialog("option", "height");
                const openBefore = dlg.dialog("isOpen");
                dlg.dialog("close");
                return { height: h, openBefore, openAfter: dlg.dialog("isOpen") };
            }""")
            exp1 = {"height": 320, "openBefore": True, "openAfter": False}
            cases.append(dict(name="plugin_method_invocation_and_args", expected=exp1, actual=r1, passed=(r1 == exp1)))

            r2 = page.evaluate("""() => {
                const dlg = $("#dlg2").dialog();
                const viaData = dlg.data("ui-dialog");
                const viaInstance = dlg.dialog("instance");
                const directReturn = viaInstance.close();
                return {
                    sameInstanceRef: viaData === viaInstance,
                    directReturnIsUndefined: directReturn === undefined,
                    openAfterInstanceClose: dlg.dialog("isOpen")
                };
            }""")
            exp2 = {
                "sameInstanceRef": True,
                "directReturnIsUndefined": True,
                "openAfterInstanceClose": False,
            }
            cases.append(dict(name="instance_data_and_instance_method", expected=exp2, actual=r2, passed=(r2 == exp2)))

            r3 = page.evaluate("""() => {
                const dlg = $("#dlg1");
                dlg.dialog("open");
                const instRet = dlg.data("ui-dialog").close();
                const pluginRet = dlg.dialog("close");
                dlg.dialog("close").css("color", "red");
                return {
                    instanceReturnUndefined: instRet === undefined,
                    pluginReturnIsJQuery: Boolean(pluginRet && pluginRet._isJQ),
                    chainedColor: dlg.css("color")
                };
            }""")
            exp3 = {
                "instanceReturnUndefined": True,
                "pluginReturnIsJQuery": True,
                "chainedColor": "rgb(255, 0, 0)",
            }
            cases.append(dict(name="return_type_chaining_vs_undefined", expected=exp3, actual=r3, passed=(r3 == exp3)))

            r4 = page.evaluate("""() => {
                const dlg = $("#dlg1");
                const ret = dlg.dialog("isOpen");
                let errName = "";
                try {
                    dlg.dialog("isOpen").css("color", "red");
                } catch (e) {
                    errName = e.name;
                }
                return { returnType: typeof ret, returnValue: ret, errorName: errName };
            }""")
            exp4 = {"returnType": "boolean", "returnValue": False, "errorName": "TypeError"}
            cases.append(dict(name="getter_return_breaks_chaining_typeerror", expected=exp4, actual=r4, passed=(r4 == exp4)))
        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-method-lab/explore-widget-method.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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