Brython如何实现JS的.bind(this)等效功能以转换cell.js代码
Brython 实现cell.js上下文绑定解决方案
核心实现方法
Brython 内置支持获取 JavaScript 侧绑定的函数上下文,直接从 javascript 模块导入 this 即可直接使用,和 JS 中的 this 行为完全一致。
完整可运行代码
<html> <body onload="brython()"> <script src="https://cdn.jsdelivr.net/gh/lesichkovm/cell@1.9.0/cell.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.10.0/brython.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.10.0/brython_stdlib.js"></script> <script type="text/python"> from browser import window, document from javascript import this def init(e): this.focus() def onkeyup(e): if e.keyCode == 13: document["list"]._add(this.value) this.value = "" def add(val): this._items.append(val) def update(): this.$components = [{'$type': 'li', '$text': item} for item in this._items] window.dispatchEvent(window.CustomEvent.new('cell-render', {'detail': { '$cell': True, 'style': "font-family: Helvetica; font-size: 14px;", '$components': [{ '$type': "input", 'type': "text", 'placeholder': "Type something and press enter", 'style': "width: 100%; outline:none; padding: 5px;", '$init': init, 'onkeyup': onkeyup, }, { '$type': "ol", 'id': "list", '_items': [], '$components': [], '_add': add, '$update': update, }] }})) </script> </body> </html>
注意事项
- 事件函数需要接收对应参数:
$init会传入当前元素实例作为参数,onkeyup会传入事件对象作为参数,需要在函数定义时预留参数位 - cell.js只支持接收数组类型的
$components属性,因此将原来的map迭代器替换为Python列表推导,写法更简洁也符合格式要求 - 原代码笔误的
$item键需要修正为$type才能正确渲染li元素
内容的提问来源于stack exchange,提问作者Rebs
相关产品推荐
相关产品推荐

