سؤال

I am trying to add a unique id to a .each loop in my underscore template, however when I use .uniqueId('XX') although it does work, it keeps changing, not something I really want it to do.

So this is my Underscore template code,

<script class='BasicText' type='text/template'>
  <% _.each(Text, function(Text) { %>
         <div contenteditable='true' id='<%= _.uniqueId('BasicText') %>' class='MyText'>
            <%= Text.text %>
         </div>
  <% }); %>
</script>

It loads form my Backbone code fine, which does what it says, it loads simple basic text from my database and displays this on my page. But the _.uniqueId keeps changing the end numbers it adds, yes they are unique but I do not want them to change.

What I have also done is set the div to be editable, so that the content can be edited and then resent to the database for an update. I have code that works fine, it executes when when the content in the div's change but right now I target the class on the div tag.

The problem with doing this is that it runs on both (there are only two basic text fields right now) div tags. So this is why I want to target only one tag at a time when the contents changes.

So can I set some sort of count on my _.each loop, then add this to my div tag?

Or can I use _.uniqueId in my code, would that work? What I mean because _.uniqueId keeps changing the end number, it should know at run time what numbers its used, right? (not sure here) If it does, then can I not get my code to use the same numbers, even if they change?

All help most welcome.

Thanks.

هل كانت مفيدة؟

المحلول

The callback passed to _.each is invoked with three parameters: the current item in the iteration, the index, and the original list. So the index you need is already provided, you can just update your template to use it. Something like this should work:

<script class='BasicText' type='text/template'>
  <% _.each(Text, function(Text, Index) { %>
         <div contenteditable='true' id='text-div-<%= Index %>' class='MyText'>
            <%= Text.text %>
         </div>
  <% }); %>
</script>

Docs here. Hope that helps, cheers!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top