开发者

Recursive jQuery Templates with custom functions causing stack overflow?

I'm creating a jQuery Template system that recursively calls the same template as needed. Most of the examples of "recursive" templates are actually just templates calling other templates, even the ones that pass around the $item object to retain custom functions. In this case, I want to call the same template with a sub-portion of the original $data (AKA $item.data) while also passing around custom template functions passed in to the options of the original tmpl call.

// original template call
$("#someTemplate").tmpl(data, {
    someFunction1: function(itemToCheck) {
        return itemToCheck.p3;
    },
    someFunction2: function(itemToCheck) {
        return itemToCheck.p1 + ", " + itemToCheck.p2;
    }
}).appendTo(".results");

<!--in-template secondary call-->
{{tmpl($data.sub, $item) "#someTemplate"}}

Full code jsFiddle

It seems that passing around $item as the options parameter for the recursive call results in the data parameter being ignored, probably because $item.data contains the original object and it simply overwrites the new data parameter. As a result, at each recursive level, I am still operating at the original caller level in the object and making no further progress in the object structure (hence the stack issue)开发者_如何学Python.

Is there some other property of $item I need to use to pass around only the custom functions without having $item.data override the template data being passed in?

Update

You definitely cannot just pass $item as the options parameter to {{tmpl}}. After looking at the code, it sets data for the new template call and then blows it away with the original $item.data through jQuery.extend a few lines later.


While I cannot seem to find a variable on $item that wraps all the custom functions, I was able to work around this issue by passing in each custom function individually from the original $item object. Not ideal, but it works.

{{tmpl($data.sub, { someFunction1: $item.someFunction1, someFunction2: $item.someFunction2 }) "#someTemplate"}}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜