Recursive jQuery Templates with custom functions causing stack overflow?

[亡魂溺海] 提交于 2019-12-12 01:54:00

问题


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).

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.


回答1:


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"}}


来源:https://stackoverflow.com/questions/7285305/recursive-jquery-templates-with-custom-functions-causing-stack-overflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!