Underscore check previous record in each

爷,独闯天下 提交于 2019-12-13 04:36:39

问题


I have an app in backbone and a template with underscore. I want to know if is possible to check a value inside a each of the previous record or something to check.
Suppose that I have record like this: { id: 1, level:1, jump_level:2 }, { id: 2, level:2, jump_level:0 }

Into my each I want to check if previous record has the same jump_level of the actual level because I want to tell that if i have to not print next record.

This is a piece of my template:

<div>
<% _.each(room2, function(room) { %>
     //I would like to write an if like this:
     // if exist previous room -> check if jump_level == level if yes don't print span
     <span> <%= room.attributes.id %></span>                                           
<% }); %>
</div>

Is possible? Thanks


回答1:


Well you can quite literally translate that to JS code:

<% _.each(room2, function(room, i) {
       if ( !(i>0 && room2[i-1].jump_level == room.jump_level) ) { %>
           <span> <%= room.attributes.id %></span>
<%     }
   }); %>



回答2:


just store the state of the previous room in a "global" variable, you could use that each consulting that state setted with a default base value the first time.



来源:https://stackoverflow.com/questions/17487411/underscore-check-previous-record-in-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!