You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:57:03