Brython equivalent of `.bind(this)`



在Javascript中,您经常需要在传递函数之前通过调用.bind(this)来为函数提供上下文。

我很欣赏Brython的工作方式有点不同。但是我想知道是否有什么东西在幕后提供了一个可访问的this类型的上下文?

具体来说,我希望将下面的cell.js示例转换为Brython

<html>
<script src="https://cdn.jsdelivr.net/gh/lesichkovm/cell@1.5.0/cell.js"></script>
<script>
var el = {
$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: function(e) { this.focus() },
onkeyup: function(e) {
if (e.keyCode === 13) {
document.querySelector("#list")._add(this.value);
this.value = "";
}
}
},
{
$type: "ol",
id: "list",
_items: [],
$components: [],
_add: function(val) { this._items.push(val) },
$update: function() {
this.$components = this._items.map(function(item) {
return { $type: "li", $text: item }
})
}
}
]
}
</script>
</html>

在被调用之前,每个函数都被绑定到相关的元素。

下面是Brython代码,但是正如你所看到的,没有与'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
def init():
print('init')
#this.focus()
def onkeyup(e):
print('onkeyup')
#if e.keyCode == 13:
#    document["list"]._add(this.value);
#    this.value = "";
def add(val):
print('add')
#this._items.append(val)
def update():
print('update')
#this.$components = map(lambda item: {'$item': 'li', '$text': item}, 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>

看起来我刚刚在文档中找到了我的答案。

javascript.this()
Returns the Brython object matching the value of the Javascript object this. It may be useful when using Javascript frameworks, eg when a callback function uses the value of this.
The module also allows using objects defined by the Javascript language. Please refer to the documentation of these objects.

相关内容

  • 没有找到相关文章

最新更新