Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent counter increment in jQuery tmpl

I'm trying to have a counter running within my jQuery tmpl so that I can perform some post-template logic. The problem is that for some reason, I can't ever get the counter to increment by 1. It seems to always increment by some random number.

Here's my HTML:

<div id='myDiv'></div>
<script id='tpl'>
    ${i=0} 
    ${i++}
    ${i++}
    ${i++}
    ${i++}
</script>

... and here's how I'm calling the templating engine:

$.tmpl($('#tpl'), {}).appendTo("#myDiv");

I've put this up on jsfiddle also: http://jsfiddle.net/2ZtRL/1/

The output I'd expect is: 0 1 2 3 4 instead, I get 0 3 7 11 15

Completely bizarre! Help!

like image 459
anushr Avatar asked Nov 10 '11 05:11

anushr


1 Answers

Try this:

<div id='myDiv'></div>
<script type="text/javascript">
    var i = -1;
    function inc(){
        return ++i;
    }
</script>

<script id='tpl'>
    ${inc()}
    ${inc()}   
    ${inc()}
    ${inc()}
    ${inc()}   
    ${inc()}
</script>

And then call your template engine code as normal. You can see it working here:

http://jsfiddle.net/2ZtRL/12

like image 103
superjaz1 Avatar answered Oct 29 '22 08:10

superjaz1