Skip to content

Commit 271efb8

Browse files
author
Franco Bugnano
committed
Simplified custom message action handling
1 parent de483aa commit 271efb8

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

lib/src/chatbox.dart

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,11 @@ class ChatBoxState extends State<ChatBox> {
145145
Timer.run(() => widget.onLoadingStateChanged?.call(LoadingState.loading));
146146

147147
execute('let chatBox;');
148+
execute('''
149+
function customMessageActionHandler(event) {
150+
JSCCustomMessageAction.postMessage(JSON.stringify(event));
151+
}
152+
''');
148153

149154
_createSession();
150155
_createChatBox();
@@ -229,7 +234,7 @@ class ChatBoxState extends State<ChatBox> {
229234
if (widget.onCustomMessageAction != null) {
230235
_oldCustomActions = Set<String>.of(widget.onCustomMessageAction!.keys);
231236
for (var action in _oldCustomActions) {
232-
execute('chatBox.onCustomMessageAction("$action", (event) => JSCCustomMessageAction.postMessage(JSON.stringify(["$action", event])));');
237+
execute('chatBox.onCustomMessageAction("$action", customMessageActionHandler);');
233238
}
234239
} else {
235240
_oldCustomActions = {};
@@ -268,11 +273,15 @@ class ChatBoxState extends State<ChatBox> {
268273
var retval = false;
269274

270275
// Register only the new event handlers
276+
//
277+
// Possible memory leak: old event handlers are not getting unregistered
278+
// This should not be a big problem in practice, as it is *very* rare that
279+
// custom message handlers are being constantly changed
271280
for (var action in customActions) {
272281
if (!_oldCustomActions.contains(action)) {
273282
_oldCustomActions.add(action);
274283

275-
execute('chatBox.onCustomMessageAction("$action", (event) => JSCCustomMessageAction.postMessage(JSON.stringify(["$action", event])));');
284+
execute('chatBox.onCustomMessageAction("$action", customMessageActionHandler);');
276285

277286
retval = true;
278287
}
@@ -415,10 +424,10 @@ class ChatBoxState extends State<ChatBox> {
415424
print('📗 chatbox._jscCustomMessageAction: ${message.message}');
416425
}
417426

418-
List<dynamic> jsonMessage = json.decode(message.message);
419-
String action = jsonMessage[0];
427+
Map<String, dynamic> jsonMessage = json.decode(message.message);
428+
String action = jsonMessage['action'];
420429

421-
widget.onCustomMessageAction?[action]?.call(MessageActionEvent.fromJson(jsonMessage[1]));
430+
widget.onCustomMessageAction?[action]?.call(MessageActionEvent.fromJson(jsonMessage));
422431
}
423432

424433
/// For internal use only. Implementation detail that may change anytime.

0 commit comments

Comments
 (0)