Nanfeng

Notes on software development, code, and curious ideas

Listening for EditBox Input Events in Cocos Creator

In Cocos Creator, you can listen for input through events exposed by the EditBox component. This example reacts when editing begins, the text changes, and editing ends.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const { ccclass, property } = cc._decorator;

@ccclass
class YourComponent extends cc.Component {

@property(cc.EditBox)
yourEditBox: cc.EditBox = null;

onLoad() {
this.yourEditBox.node.on('editing-did-began', this.onEditingDidBegan, this);
this.yourEditBox.node.on('text-changed', this.onTextChanged, this);
this.yourEditBox.node.on('editing-did-ended', this.onEditingDidEnded, this);
}

onEditingDidBegan() {
cc.log('The user started editing');
}

onTextChanged() {
cc.log('The input changed', this.yourEditBox.string);
}

onEditingDidEnded() {
cc.log('The user finished editing');
}
}

The three events are:

  • editing-did-began: fired when the user starts editing the input.
  • text-changed: fired whenever the text changes.
  • editing-did-ended: fired when the user finishes editing.

Use whichever events your feature needs. Their callbacks can update the UI, validate input, or perform other actions. Register the listeners at an appropriate lifecycle point such as onLoad, and remove them when the component is destroyed to avoid stale listeners or memory leaks.

+