Saturday, 18 March 2017

Node JS sort array passed with Handlebars template client side

I'm developing a simple web app, using nodeJS, express, MongoDB and Handlebars. Server side I use express-handlebars:

var exphbs = require('express-handlebars');
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs(
    {
        defaultLayout:'layout',
        helpers: { /*my helpers*/}}));

So, when I query the db I want to show the result to the client in a page: /* some code */ router.get('/', function(req, res) {

    /*query to mongo DB with mongoose*/
    Coll.find(queryParams, function(err,coll){
        if(err) {
                    console.log(err);
                    throw err;
                }
                else {
                    res.render('index', {'coll': coll});
                }
    });

Showing the result is quite simple with handlebars:





But I would like to allow the user to sort this array of elements without interact again with the server, given that the query results would be the same and will change only the order. the html code would be:

<select id=id>
<option>sort1</option>
<option>sort2</option>
</select>



<script>
$(document).ready(function () {
    $('#id').change(function(){

//DO SOME STUFF WITH LIST
});
</script>

Does it exist a method to sort client-side the array passed via res.render(...) ? If the user choose an option in a select tag, can I use AJAX to modify the list? And how? (always without interact with the server and without execute again the same query on mongoDB)

PS: I'm a beginner with nodeJS and Handlebars, please be patient!



via Giacomo Resci

No comments:

Post a Comment