bitflood
bitflood

Reputation: 441

Server Sent Events in Ember JS

I have an App in which on clicking a link the browser needs to trigger something on server and client is supposed to get progress of it. SSE is a good candidate for this but I am unable to figure this out in ember (which I am learning).

I tried with the template execute:

<script type="text/x-handlebars" data-template-name="execute">
    <script>
       if(typeof(EventSource)!=="undefined") {
          var source=new EventSource("/execute/flow");
          source.onmessage=function(event) {
              if(event.data == 'end') {
                source.close();
              }else{
                document.getElementById("flow_result").innerHTML+= event.data + "<br>";
              }
          };
       } else {
          document.getElementById("flow_result").innerHTML="Sorry, your browser does not support server-sent events...";
       }
    }
    <script>
<script>

Somewhere on the page there is a link using {{#link-to 'execute'}} which triggers this template. But somehow this SSE javascript is not executed at all.

Questions:

1) What I am I doing wrong? (I suspect that I should not put javascript code in template) 2) Is there any good example of using SSE with ember js?

Upvotes: 3

Views: 1201

Answers (1)

Alexphys
Alexphys

Reputation: 408

Don't pass code in the template. Handle whatever actions you like in the controllers and routes of your application. For sse you can do the following:

App.ApplicationController = Ember.Controller.extend({
  init: function() {
    var eventSource;
    eventSource = new EventSource(your-event-source);
    return eventSource.addEventListener(your-event-to-listen, function(e) {
      var data;
      return data = $.parseJSON(e.data);
      //Do whatever else you want in here with your data
    });
  }
});

Upvotes: 5

Related Questions