研究调查问卷:请告诉我们您使用 Blockly 的体验
开始调查问卷
活动
工作区中的每项更改都会触发事件。这些事件会完整描述每次更改之前和之后的状态。
监听事件
工作区包含 addChangeListener
和 removeChangeListener
方法,
用于监听事件流。其中一个例子是
实时生成代码。
另一个示例是“最大分块限制”演示。与往常一样,这两个例子并不关心触发
事件。它们只会查看工作区的当前状态。
更复杂的事件监听器会查看触发事件。通过
以下示例会检测用户何时创建了第一条评论,
发出提醒,然后停止监听,从而不再触发其他提醒。
function onFirstComment(event) {
if (event.type == Blockly.Events.BLOCK_CHANGE &&
event.element == 'comment' &&
!event.oldValue && event.newValue) {
alert('Congratulations on creating your first comment!')
workspace.removeChangeListener(onFirstComment);
}
}
workspace.addChangeListener(onFirstComment);
要监听浮出控件内发生的任何事件,监听器可
添加到浮出控件的工作区。
var flyoutWorkspace = yourWorkspace.getFlyout().getWorkspace();
flyoutWorkspace.addChangeListener(onFirstComment);
区块还有另一种监听事件流的方法。块可以定义 onchange
函数,也可以使用 setOnChange 设置一个函数,以便在块的工作区发生更改时调用该函数。
事件类型
如需了解各个事件的相关信息,请参阅参考文档。
演示
如需了解如何使用事件执行一些很酷的操作,您可以查看镜像演示。此演示版有两个使用事件保持同步的 Blockly 工作区。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-11-08。
[null,null,["最后更新时间 (UTC):2024-11-08。"],[[["Every workspace change triggers an event detailing the before and after state."],["Workspaces offer methods (`addChangeListener`, `removeChangeListener`) to listen for these events."],["Events can be used for various purposes like real-time code generation or triggering actions based on specific changes (e.g., a new comment)."],["Blocks can also have individual change listeners using the `onchange` function or `setOnChange`."],["Comprehensive event details are available in the Blockly reference documentation."]]],["Workspace changes trigger events, describing the before and after states. Listeners can be added using `addChangeListener` and removed with `removeChangeListener`. Listeners can react to specific events, like the creation of a comment, or monitor all events. Flyout events can be monitored by adding a listener to the flyout's workspace. Blocks can use an `onchange` function to listen for changes in their workspace. There are several event types as described in the documentation.\n"]]