samedi 8 octobre 2016

Ember 2.8: Should I randomize an array as a handlebars helper or write a function in the server side?

I have a function that takes in an array and randomizes the values inside of it.

shuffle([1,2,3,4]) => [2,4,1,3];

Now, I have succesfully used this function in my server side code for my ember app like so:

mirage config.js file

this.get('/games/:id', function (db, request) {
    var game = games.find((game) => request.params.id === game.id);
    var cardsShuffled = shuffle(game.attributes.cards);
    game.attributes.cards = cardsShuffled;
    return {data: game};

  });

And then rendering my handlebars view like so:

play.hbs

<div>
  
    
  
</div>

But I was wondering if it is better to create some sort of handlebars helper? I'm new to ember, but it doesn't look too clean to me to have the backend do that kind of logic. So here's what I was thinking:

shuffle-array.js helper

import Ember from 'ember';

export function shuffleArray(array) {

  var m = array.length, t, i;

  while (m) {

    i = Math.floor(Math.random() * m--);

    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }
  return array;
};


export default Ember.Helper.helper(shuffleArray);

And then somehow use it like so (tried this. failed):

play.hbs (revised)

<div>
  
  
    
  
</div>

So I guess my question is two-fold: Is it acceptable/unnaceptable to have this kind of logic coming from the mirage backend? Also, what is the best way to have a handlebars helper implement this?




Aucun commentaire:

Enregistrer un commentaire