Miguel
Miguel

Reputation: 1211

Add Jade blocks of content in the client-side with jQuery

I have some content that loads from Jade when page loads (for example, a connected users list). This content is dynamic and client is notified of its changes via socket.io messages. A jQuery script in client-side must add the new content or remove the old one.

The problem is that the new content can be very complex (for example, all the information of users) and I've to rewrite the HTML code in the client-side script (and jQuery is not intended for that).

I've tried to clone and edit an existing structure (can be hidden) but I think it's no the best way.

Example

Server-side

#usersList
    each user in users
        .userBox
            .userName #{user.name}
            .userCountry #{user.country}
            .userMail #{user.mail}

Client-side

websocket.on('newUser', function(user) {
    $('<div class="userBox">'+
        '<div class="userName">' + user.name +'</div>'+
        '<div class="userCountry">' + user.country +'</div>'+
        '<div class="userMail">' + user.mail +'</div>'+
    '</div>').appendTo($('#usersList'));
});

Client-side code is horrible. I wonder if I could have a block of content in Jade and do this.

websocket.on('newUser', function(user) {
    $(jade.userBox(user)).apprendTo('#usersList');
});

If it's not possible, what is the best way?

Upvotes: 1

Views: 1615

Answers (1)

Dslayer
Dslayer

Reputation: 1126

I would not use jade to render the users because I would have 2 ways to insert users, one for when loading the page and a another for when updating. That was going to be too complex to handle with the class that handles users. So I just use jade to create the page template (placeholders) and get data to client side.

var local_data ={}
local_data.users =!{JSON.stringify(usersList)}
div#users(class="ui-bar ui-bar-h")

js:

users.add(data);

Where users.add() will actually store userdata and options in an array and do some DOM manip with jquery

This can used when loading and when updating seamlessly

Upvotes: 1

Related Questions