I am trying to attach a DOM element with a callback in JavaScript. Basically, the following is what I want:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="http://static.robotwebtools.org/roslibjs/current/roslib.min.js"></script>
<script src="http://static.robotwebtools.org/EventEmitter2/current/eventemitter2.min.js"></script>
<script>
var ros = new ROSLIB.Ros({ url: "ws://localhost:9090" });
var listener = new ROSLIB.Topic({
ros: ros,
name: "/listener",
messageType: "std_msgs/String",
element: document.getElementById("hi") // this is added to show my need
});
listener.subscribe(function (event) {
// do crazy things here. let say replace the text
event.element.innerHTML = event.message.data; // this is added to show my need
});
</script>
</head>
<body>
<div id="hi"> hello world </div>
</body>
</html>
I want to use the DOM element inside the callback, which was declared while initializing the listener. I found a similar question here but could not make it work in this case.
function Subscriber(element, topic) {
var listener = new ROSLIB.Topic({
ros: ros,
name: topic,
messageType: "std_msgs/String"
});
listener.addEventListener("subscribe", this, false);
this.listener = listener;
this.element = element;
}
Subscriber.prototype.handleEvent = function (event) {
switch (event.type) {
case "subscribe":
this.element.dispatchEvent(new CustomEvent("subscribe", { details: { msg: message, e: element } }));
}
};
var element = document.getElementById("hi");
var topic = "/listener";
var subscriber = new Subscriber(element, topic);
subscriber.handleEvent(function (event) {
// do crazy things here. let say replace the text
event.details.e.innerHTML = event.details.msg.data;
});
As listener
is a custom object, addEventListener
is unavailable. Therefore, the following error is reported at the console:
listener.addEventListener("subscribe", this, false);
Uncaught TypeError: listener.addEventListener is not a function
How to modify the subscribe
callback to bind a DOM element with it in JavaScript?