Registering A Callback

OK I got this and @Dave was exactly right. You need to have a listener for the exact event type you defined in your core such “Temperature” or “spark-hq/motion”. It would still be nice to learn to listen to the entire fire-hose of public events.

Here’s my HTML–the Temperature events don’t come as fast as some others so be patient.

<!DOCTYPE HTML>
<html>
<body>
    Event: <span id="foo">Events will appear here.</span>
     
    <br><br>
    <button onclick="start()">Start</button>
 
    <script type="text/javascript">
    function start() {

        document.getElementById("foo").innerHTML = "OK you clicked it...";
        console.log("Clicked...");
 
        var eventSource = new EventSource("https://api.spark.io/v1/events/?access_token=<<hex number here>>");

        eventSource.addEventListener('open', function(e) {
            console.log("Opened!"); },false);
         
        eventSource.addEventListener('error', function(e) {
            console.log("Errored!"); },false);
         
        eventSource.addEventListener('Temperature', function(e) {
            console.log("Enter event listener");
            console.log(event.data);
            document.getElementById("foo").innerHTML = "Here it comes...";
            document.getElementById("foo").innerHTML += event.data + "<br>";
        }, false);
    }
    </script>
</body>
</html>

4 Likes