Search code examples
jsrenderjsviews

Alternate approach to <span class="item-in-loop" data-index="{^{:#index}}"></span>


Sorry for the noobish question. I feel there has to be a better way, but I'm not seeing it. I don't want to have to do a loop in the button click looking for an ID. I just want to pass the index to be removed.

Here's what I'm thinking I have to do

html

<div id="list">
   {^{for items}}
      <div class="list-item">
         ...
         <a href="#" class="remove-list-item">Remove
            <span class="remove-list-item-index hide">{^{:#index}}</span>
         </a>
      </div>
   {{/for}}
</div>

js

$('a.remove-list-item').click(function () {  
   $.observable(listArray).remove(parseInt($(this).children('span.remove-list-item-index').text()));
});

Here's what I want to do

html

<div id="listing">
   {^{for items}}
      <div class="listing-item"> 
         ...
         <a href="#" data-index="{^{:#index}}">Remove</a>
      </div>
   {{/for}}
</div>

js

$('a.remove-list-item').click(function () {  
   $.observable(listArray).remove(parseInt($(this).attr('data-index')));
});

Solution

  • You can get the current view for any element, using var view = $.view(element).

    And for views corresponding to {^{for items}} block, each view has an index property.

    So you can do:

    $('a.remove-list-item').click(function () {  
       $.observable(listArray).remove($.view(this).index);
    });
    

    which is simpler than either of your suggested approaches.

    There are a number of samples using that approach, e.g. http://www.jsviews.com/#samples/editable/tags