Cellydy
Cellydy

Reputation: 1339

Sails.js - Update variable from socket data

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?

Upvotes: 0

Views: 99

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

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>`;

Upvotes: 2

Related Questions