0

I'm trying to update my view when I receive new data via a websocket using Sails.js.

in my controller welcome.js I have:

module.exports = {
    fn: async function (inputs, exits) {
        var allDeals = await Deal.find({});
        return exits.success({deals:allDeals});
    }
};

in my view welcome.ejs I have:

<% _.each(deals, function (deal) { %>
    <div class="dealTitle"><%= deal.title %></div>
<% }) %>

And this data is displayed correctly.

I've set up a websocket to listen to new deals being added in welcome.page.js in the mounted function:

mounted: async function() {
    io.socket.get('/feed/subscribe', function(data, jwr) {
      io.socket.on('new_entry', function(entry) {
        console.log(entry); 
      });
     });
},

Once a new deal is created, the it shows up in the console thanks to the console log correctly.

My question is as follows: how do I update the deals variable in <% _.each(deals, function (deal) { %> with the data I'm currently console.logging, so that the new deals are rendered in the for loop?

Cellydy
  • 1,365
  • 3
  • 15
  • 27

1 Answers1

2

The ejs only exists on the server, so you cannot access that . However you could just wrap the divs in a parent:

<div id="deals" >
 <% _.each(deals, function (deal) { %>
<div class="dealTitle"><%= deal.title %></div>
<% }) %>
</div>

And then whenever a new entry arrives, add some html to that deals div:

 document.getElementById("deals").innerHTML += `<div class="dealTitle">${entry.title}</div>`;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • That's exactly what I thought I would need to do but I wanted to avoid this as I'm duplicating the HTML
    <%= deal.title %>
    in the for-loop and then again in the innerHTML appending. Is there a way I can template this so I don't have to duplicate code?
    – Cellydy Oct 06 '18 at 16:32
  • @cellydy never did this, but it seems possible: https://stackoverflow.com/questions/41001619/client-side-and-server-side-rendering-of-ejs-template – Jonas Wilms Oct 06 '18 at 16:59