部件库(Widget Factory)
核对使用 $.widget('custom.colorize') 构建有状态小部件的完整生命周期:options、_create/_refresh/_destroy、_on/_trigger 取消机制、_setOptions/_setOption 校验及自定义选择器。
学完这一章,你能够
- 核对使用 $.widget('custom.colorize') 构建有状态小部件的完整生命周期:options、_create/_refresh/_destroy、_on/_trigger 取消机制、_setOptions/_setOption 校验及自定义选择器。
使用 $.widget() 构建有状态的 custom.colorize 小部件
jQuery UI 部件库(`jquery.ui.widget.js`)提供了与官方全部小部件同源的抽象层,用于快速开发有状态的 jQuery 插件,详细规范见官方 Widget Factory API 文档。本节完整实例通过 `$.widget( "custom.colorize", { ... } )` 演示核心生命周期:在 `options` 中声明默认 RGB 通道(`255, 0, 0`)与 `change`/`random` 回调;在 `_create()` 中附加 `.custom-colorize` 类、插入“改变”按钮并用 `this._on()` 绑定 `click -> "random"`(禁用态自动跳过);在 `_refresh()` 中更新背景色并 `this._trigger( "change" )`;在公共方法 `random()` 中借 `this._trigger( "random", event, colors ) !== false` 支持外部回调否决随机色;在 `_setOptions()` 中以 `_superApply( arguments )` 批量写入并统一刷新,在 `_setOption()` 中拦截超出 `0..255` 范围的非法通道值;在 `_destroy()` 中移除生成按钮、类名与背景色。页面以默认配置、自定义红蓝值及“仅允许 `ui.green > 128`”回调三种方式分别初始化三个区块,并配合自定义伪选择器 `:custom-colorize` 一键切换 `disable`/`enable` 或批量置黑。
本站离线 Playwright Chromium 完整复现该部件并实测四组行为:其一,三个实例初始背景色依次为 `rgb(255, 0, 0)`、`rgb(60, 0, 60)`、`rgb(255, 128, 0)`,生成 3 个 `.custom-colorize-changer` 按钮且各触发 1 次初始 `change`;其二,调用 `random()` 将 `#my-widget1` 更新为 `rgb(50, 100, 150)`,而 `#my-widget3` 对 `green=80` 候选色返回 `false` 保持原色、对 `green=200` 放行并更新为 `rgb(10, 200, 30)`;其三,点击 `#disable` 将全部 3 个 `:custom-colorize` 实例置为禁用态后,点击内部“改变”按钮被 `_on` 拦截(背景色不变),再次切换启用并点击 `#black` 后三实例同步变为 `rgb(0, 0, 0)`;其四,传入越界值 `red=300` 与 `green=-10` 均被 `_setOption` 拒绝,传入合法 `{ red: 120, green: 180, blue: 240 }` 生效为 `rgb(120, 180, 240)`,对 `#my-widget1` 调用 `destroy` 后按钮与 `.custom-colorize` 移除、背景复位为透明且 `:custom-colorize` 计数由 3 降至 2。
在离线 Chromium 中实测 custom.colorize 部件初始化、回调否决、禁用拦截与销毁清理
"""Offline Chromium lab for jQuery UI Ch43: Widget Factory custom.colorize widget."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Widget Factory colorize Lab</title>
<style>
body { margin: 12px; font-family: sans-serif; }
.custom-colorize { font-size: 20px; position: relative; width: 75px; height: 75px; display: inline-block; margin-right: 10px; }
.custom-colorize-changer { font-size: 10px; position: absolute; right: 0; bottom: 0; }
</style>
</head>
<body>
<div>
<div id="my-widget1">改变颜色</div>
<div id="my-widget2">改变颜色</div>
<div id="my-widget3">改变颜色</div>
<button id="disable">切换 disabled 选项</button>
<button id="black">改为黑色</button>
</div>
<script>
// Minimal faithful Widget Factory core supporting $.widget("custom.colorize", proto)
const widgetStore = new Map();
const widgetRegistry = {};
window.__changeCounts = { "my-widget1": 0, "my-widget2": 0, "my-widget3": 0 };
window.__nextColorsQueue = [];
function createWidgetFactory(fullName, proto) {
const [ns, name] = fullName.split(".");
const key = ns + "-" + name;
widgetRegistry[key] = { ns, name, proto };
function BaseWidget(element, options) {
this.element = element;
this.widgetFullName = key;
this.options = Object.assign({ disabled: false }, proto.options, options || {});
this._boundListeners = [];
widgetStore.set(element, this);
this._create();
}
BaseWidget.prototype._super = function(k, v) {
this.options[k] = v;
};
BaseWidget.prototype._superApply = function(args) {
const hash = args[0] || {};
for (const [k, v] of Object.entries(hash)) {
this._setOption(k, v);
}
};
BaseWidget.prototype._setOptions = function(options) {
for (const [k, v] of Object.entries(options)) {
this._setOption(k, v);
}
};
BaseWidget.prototype._setOption = function(key, value) {
this.options[key] = value;
};
BaseWidget.prototype._on = function(target, handlers) {
for (const [evName, method] of Object.entries(handlers)) {
const fn = (ev) => {
if (this.options.disabled) return;
const handler = typeof method === "string" ? this[method] : method;
handler.call(this, ev);
};
target.addEventListener(evName, fn);
this._boundListeners.push([target, evName, fn]);
}
};
BaseWidget.prototype._trigger = function(type, ev, data) {
const cb = this.options[type];
if (type === "change" && window.__changeCounts[this.element.id] !== undefined) {
window.__changeCounts[this.element.id]++;
}
if (typeof cb === "function") {
return cb.call(this.element, ev || {}, data || {});
}
return true;
};
BaseWidget.prototype.option = function(k, v) {
if (typeof k === "string" && arguments.length === 1) return this.options[k];
if (typeof k === "string") {
this._setOptions({ [k]: v });
return this;
}
if (typeof k === "object") {
this._setOptions(k);
return this;
}
return this.options;
};
BaseWidget.prototype.disable = function() {
this.option("disabled", true);
this.element.classList.add("ui-state-disabled");
};
BaseWidget.prototype.enable = function() {
this.option("disabled", false);
this.element.classList.remove("ui-state-disabled");
};
BaseWidget.prototype.destroy = function() {
this._boundListeners.forEach(([t, ev, fn]) => t.removeEventListener(ev, fn));
this._boundListeners = [];
if (this._destroy) this._destroy();
widgetStore.delete(this.element);
};
Object.assign(BaseWidget.prototype, proto);
return BaseWidget;
}
const Colorize = createWidgetFactory("custom.colorize", {
options: { red: 255, green: 0, blue: 0, change: null, random: null },
_create() {
this.element.classList.add("custom-colorize");
this.element.style.userSelect = "none";
this.changer = document.createElement("button");
this.changer.textContent = "改变";
this.changer.className = "custom-colorize-changer";
this.element.appendChild(this.changer);
this._on(this.changer, { click: "random" });
this._refresh();
},
_refresh() {
this.element.style.backgroundColor = `rgb(${this.options.red}, ${this.options.green}, ${this.options.blue})`;
this._trigger("change");
},
random(event) {
const colors = window.__nextColorsQueue.length
? window.__nextColorsQueue.shift()
: {
red: Math.floor(Math.random() * 256),
green: Math.floor(Math.random() * 256),
blue: Math.floor(Math.random() * 256)
};
if (this._trigger("random", event, colors) !== false) {
this.option(colors);
}
},
_destroy() {
this.changer.remove();
this.element.classList.remove("custom-colorize");
this.element.style.userSelect = "";
this.element.style.backgroundColor = "transparent";
},
_setOptions() {
this._superApply(arguments);
this._refresh();
},
_setOption(key, value) {
if (/red|green|blue/.test(key) && (value < 0 || value > 255)) {
return;
}
this._super(key, value);
}
});
function queryCustomColorize() {
return Array.from(widgetStore.keys());
}
window.queryCustomColorize = queryCustomColorize;
window.getWidget = id => widgetStore.get(document.getElementById(id));
// Initialize 3 widgets in 3 distinct ways matching source demo
new Colorize(document.getElementById("my-widget1"));
new Colorize(document.getElementById("my-widget2"), { red: 60, blue: 60 });
new Colorize(document.getElementById("my-widget3"), {
green: 128,
random(event, ui) {
return ui.green > 128;
}
});
document.getElementById("disable").addEventListener("click", () => {
const all = queryCustomColorize().map(el => widgetStore.get(el));
if (all[0].option("disabled")) {
all.forEach(w => w.enable());
} else {
all.forEach(w => w.disable());
}
});
document.getElementById("black").addEventListener("click", () => {
queryCustomColorize().forEach(el => {
widgetStore.get(el).option({ red: 0, green: 0, blue: 0 });
});
});
</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(viewport={"width": 800, "height": 400})
page.set_content(HTML)
# Case 1: 3 initialization modes & initial colors + change events
r1 = page.evaluate("""() => ({
colors: ['my-widget1', 'my-widget2', 'my-widget3'].map(id => getComputedStyle(document.getElementById(id)).backgroundColor),
changerButtons: document.querySelectorAll('.custom-colorize-changer').length,
initialChangeCounts: Object.assign({}, window.__changeCounts),
selectorCount: window.queryCustomColorize().length
})""")
exp1 = {
"colors": ["rgb(255, 0, 0)", "rgb(60, 0, 60)", "rgb(255, 128, 0)"],
"changerButtons": 3,
"initialChangeCounts": {"my-widget1": 1, "my-widget2": 1, "my-widget3": 1},
"selectorCount": 3,
}
cases.append(dict(name="three_init_modes_and_initial_colors", expected=exp1, actual=r1, passed=(r1 == exp1)))
# Case 2: random() method & cancelable random callback (ui.green > 128)
page.evaluate("""() => {
window.__nextColorsQueue = [
{ red: 50, green: 100, blue: 150 },
{ red: 20, green: 80, blue: 40 },
{ red: 10, green: 200, blue: 30 }
];
}""")
page.locator("#my-widget1 .custom-colorize-changer").click()
w1_after = page.evaluate("() => getComputedStyle(document.getElementById('my-widget1')).backgroundColor")
page.locator("#my-widget3 .custom-colorize-changer").click()
w3_vetoed = page.evaluate("() => getComputedStyle(document.getElementById('my-widget3')).backgroundColor")
page.locator("#my-widget3 .custom-colorize-changer").click()
w3_accepted = page.evaluate("() => getComputedStyle(document.getElementById('my-widget3')).backgroundColor")
r2 = {"w1Random": w1_after, "w3VetoedLowGreen": w3_vetoed, "w3AcceptedHighGreen": w3_accepted}
exp2 = {
"w1Random": "rgb(50, 100, 150)",
"w3VetoedLowGreen": "rgb(255, 128, 0)",
"w3AcceptedHighGreen": "rgb(10, 200, 30)",
}
cases.append(dict(name="random_method_and_cancelable_callback", expected=exp2, actual=r2, passed=(r2 == exp2)))
# Case 3: Custom selector :custom-colorize disable/enable & batch black option
page.click("#disable")
page.evaluate("() => { window.__nextColorsQueue = [{ red: 1, green: 2, blue: 3 }]; }")
page.locator("#my-widget1 .custom-colorize-changer").click()
while_disabled = page.evaluate("""() => ({
disabledFlag: window.getWidget('my-widget1').option('disabled'),
colorUnchangedWhileDisabled: getComputedStyle(document.getElementById('my-widget1')).backgroundColor
})""")
page.click("#disable")
enabled_again = page.evaluate("() => window.getWidget('my-widget1').option('disabled')")
page.click("#black")
all_black = page.evaluate("() => ['my-widget1', 'my-widget2', 'my-widget3'].map(id => getComputedStyle(document.getElementById(id)).backgroundColor)")
r3 = {
"disabledFlag": while_disabled["disabledFlag"],
"colorUnchangedWhileDisabled": while_disabled["colorUnchangedWhileDisabled"],
"disabledAfterToggleBack": enabled_again,
"allBlackColors": all_black,
}
exp3 = {
"disabledFlag": True,
"colorUnchangedWhileDisabled": "rgb(50, 100, 150)",
"disabledAfterToggleBack": False,
"allBlackColors": ["rgb(0, 0, 0)", "rgb(0, 0, 0)", "rgb(0, 0, 0)"],
}
cases.append(dict(name="custom_selector_disable_enable_and_black_batch", expected=exp3, actual=r3, passed=(r3 == exp3)))
# Case 4: _setOption 0..255 validation guard & _destroy cleanup
r4 = page.evaluate("""() => {
const w1 = window.getWidget('my-widget1');
w1.option('red', 300);
w1.option('green', -10);
const afterInvalid = getComputedStyle(document.getElementById('my-widget1')).backgroundColor;
w1.option({ red: 120, green: 180, blue: 240 });
const afterValid = getComputedStyle(document.getElementById('my-widget1')).backgroundColor;
w1.destroy();
const el1 = document.getElementById('my-widget1');
return {
afterInvalid,
afterValid,
hasClassAfterDestroy: el1.classList.contains('custom-colorize'),
hasChangerAfterDestroy: el1.querySelector('.custom-colorize-changer') !== null,
bgAfterDestroy: getComputedStyle(el1).backgroundColor,
remainingSelectorCount: window.queryCustomColorize().length
};
}""")
exp4 = {
"afterInvalid": "rgb(0, 0, 0)",
"afterValid": "rgb(120, 180, 240)",
"hasClassAfterDestroy": False,
"hasChangerAfterDestroy": False,
"bgAfterDestroy": "rgba(0, 0, 0, 0)",
"remainingSelectorCount": 2,
}
cases.append(dict(name="setOption_validation_and_destroy_cleanup", expected=exp4, actual=r4, passed=(r4 == exp4)))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 3 种初始化颜色与 3 次 change、random 回调否决 green<=128 与放行 green>128、:custom-colorize 批量禁启用与置黑,以及 _setOption 0..255 拦截与 destroy 清理。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:b0d742498f494bb5614f93bdcbe8bbfb0b07b1a226ec402b4c943c796fb3784c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ecee9b22a62531f9a28777f2b2038f6fb52eb53232901289da285dd23d2b6b9d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在自定义小部件中,为什么推荐用 `this._on( this.changer, { click: "random" } )` 而非直接调用原生 `addEventListener` 或 `.on()`?
展开参考解答
`this._on()` 会自动将回调的 `this` 绑定到小部件实例、在 `disabled: true` 时自动屏蔽事件触发,并在调用 `destroy()` 时自动解绑全部监听器以防止内存泄漏。