lundi 4 janvier 2016

Ember moving objects from one array to another

I have a navigation service that expects each route to define the items that the navigation will show. There is a visible part of the navigation and there is a hidden part of the navigation. The hidden part is revealed when the user clicks on a menu icon. The visible ones show in a nav bar at the bottom of the page

enter image description here

In the route I pass the nav items like so

this.get('navigationService').set('navigationMenuItems',[
    Ember.Object.create({
        icon: "user",
        size: "(totalSpace / 2)"
    }),
    Ember.Object.create({
        icon: "items",
        size: "(totalSpace / 2)"
    }),
    Ember.Object.create({
        icon: "my-items",
        size: 60
    }),
    Ember.Object.create({
        icon: "event",
        size: 60
    }),
    Ember.Object.create({
        icon: "ticket",
        size: 60
    }),
    Ember.Object.create({
        icon: "cart",
        size: 60
    }),
    Ember.Object.create({
        icon: "donate",
        size: 60
    }),
]);

In my navigationService I work with this array to build two new arrays, a visible one and an invisible one

navigationMenuItems: [],
visibleNavItems: [],
hiddenNavItems: [],
_initializeNavigation: Ember.observer('navigationMenuItems',function(){
    var self = this;
    self.get('visibleNavItems').clear();
    self.get('hiddenNavItems').clear();
    var items = self.get('navigationMenuItems').toArray();
    var totalSpace = Ember.$(window).innerWidth() - 60;
    var availableSpace = totalSpace;
    items.forEach(function(item){
      var width = eval(item.size);
      if(width <= availableSpace) {
        availableSpace -= width;
        self.get('visibleNavItems').pushObject(item);
      }else{
        self.get('hiddenNavItems').pushObject(item);
      }
    })
})

I'm iterating over a copy of the items (I was attempting to remove the items and push them into the new arrays) and check if the size they specified fits in the available space, if it does I push it into the visible items, update the new available space and move on.

What I really would like to do is stop at the first item that doesn't fit, and rather than continue iterating over the remaining items, push all of the rest into the hidden items array and stop the loop.

I was having some issues removing items from the initial array and pushing those into the proper arrays so for now this is working, but I feel like it could be done better and more efficiently.

Can someone help me get this to where to moves the item from the copied array into the new array so that in the else I can assume I an push the remaining into the hidden array and stop the loop?




Aucun commentaire:

Enregistrer un commentaire