Hi,
i can create custom event object inmherited from Event, examply:
type
OpenSocketEvent* = ref OpenSocketEventObj
OpenSocketEventObj = object of Event
url: string
proc newOpenSocketEvent(url: string): OpenSocketEvent =
result = OpenSocketEvent(`type`: $openSocket,
url: url)
proc onLoad (event: Event) =
let ws_protocol = if window.location.protocol == HTTP: WS else: WSS
let ws_location = &"{ws_protocol}//{window.location.host}/ws"
var socket = newWebSocket(ws_location)
let openSocketEvent = newOpenSocketEvent ws_location
# openSocketEvent.url = ws_location
socket.onOpen = proc (e:MessageEvent) =
window.dispatchEvent(openSocketEvent)
This example is compiled without errors.
When I run it (in browser), in console I have this error:
terminal.js:4382 Uncaught TypeError: Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.
at WebSocket.HEX3Aanonymous_603979867 (terminal.js:4382)
HEX3Aanonymous_603979867 @ terminal.js:4382
This means, that
window.dispatchEvent(openSocketEvent)
cannot call with inherited object?
thanks
Here is javascript code, which I can rewrite in Nim.
I have this problem in Nim:
Pure vanilla javascript version works.
const HTTP = "http:"
const HTTPS = "https:"
const WS = "ws:"
const WSS = "wss:"
const Load = "load";
const OpenSocket = "openSocket";
const MessageSocket = "messageSocket";
function onLoad(event) {
var ws_protocol = WS;
if (window.location.protocol == HTTPS) {
ws_protocol = WSS;
}
let ws_location = ws_protocol + "//" + window.location.host + "/ws";
console.log("webscoket url " + ws_location);
var socket = new WebSocket(ws_location)
const openSocketEvent = new CustomEvent(OpenSocket, { detail: { url: ws_location } });
socket.onopen = function (event) {
window.dispatchEvent(openSocketEvent);
socket.send("hello");
};
socket.onmessage = function (event) {
// console.log("MESSAGE:\n\n" + event.data);
const messageSocketEvent = new CustomEvent(MessageSocket, { detail: { msg: event.data } });
window.dispatchEvent(messageSocketEvent);
}
}
function onOpenSocket(event) {
console.log("open websocket " + event.detail.url);
}
function onMessageSocket(event) {
console.log("MESSAGE: " + event.detail.msg);
}
window.addEventListener(Load, onLoad);
window.addEventListener(OpenSocket, onOpenSocket);
window.addEventListener(MessageSocket, onMessageSocket);