开发者

JQuery Template - Calls ${$item.function()} more than is specified in the template

开发者 https://www.devze.com 2023-04-09 10:11 出处:网络
Jquery-tmpl seems to call functions you attach to item multiple times. JSfiddle: http://jsfiddle.net/abQwc/2/

Jquery-tmpl seems to call functions you attach to item multiple times.

JSfiddle: http://jsfiddle.net/abQwc/2/

The console.log's show rowCount got called 4 times for each item rendered by the template.

Template:

<h1 class="${$item.rowCount() % 2 == 0 ? "even" : "odd"}">${Name} - ${Payload}<开发者_运维知识库;/h1

Data:

    data = [
        { Name: "1", Payload: "Data1" },
        { Name: "2", Payload: "Data2" },
        { Name: "3", Payload: "Data3" } 
    ]

Script:

    $(function() {$( "#template" )
        .tmpl(data, {
            rowCount: function(){
                var rowCount = 0;
                return function(){
                    console.log(this.data.Payload);
                    return ++rowCount;
                }
            }()
        })
        .appendTo( "body" )})

Why? I've already figured out how to get around it, but it reeks of witchcraft.


I replaced:

${$item.rowCount() % 2 == 0 ? "even" : "odd"}
...
return function(){
    console.log(this.data.Payload);
    return ++counter;
}

with

${$item.rowCount()}
....
return function() {
    console.log(this.data.Payload);
    return (++counter) % 2 ? 'even' : 'odd';
}

and was able to get it to work. However, the Options parameter was still getting executed 4 times for each item. I believe calculations like that in tmpl are still iffy at best.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号