gpt4 book ai didi

javascript - 闭包中的 jquery tmpl

转载 作者:行者123 更新时间:2023-11-29 22:32:22 28 4
gpt4 key购买 nike

我正在研究这个小型 javascript 库,并遵循各种建议,出于各种原因(变量封装、代码隐藏等),我将我的功能包装在闭包中。因为我查询一个 JSON 网络服务并显示结果,所以我也使用 jquery tmpl 引擎。
我想我明白闭包有什么好处,但我肯定不了解它们。这意味着我完全迷失在所有这些范围变化和诸如此类的事情之间。特别烦人的是我得到的这个异常(exception)。考虑以下代码(有问题的代码的简化丑陋版本,但它重现了问题)

// something would be the object that handles all the library functionality
var something = function(){

// creating a local function that goes as a parameter into the Array.filter
function isBar(data){
return data.name === "bar";
}

// the template code
var bla = "<h1>${name}<\h1><h2>${attribute.filter(isBar)[0].value}</h2>";

// precompiling the the template
$.template("test", bla);

// and returning a function that should render the template with the provided data
return {
funny: function(){
$.tmpl("test", [{"name":"Fo", "attribute":[{"name":"bar", "value":"how"}]},
{"name":"Foo", "attribute":[{"name":"fnord","value":"can"}]},
{"name":"Fooo", "attribute":[{"name":"bar","value":"this"}]},
{"name":"Foooo", "attribute":[{"name":"Bar", "value":"be"}]}
]);
}
}
}();
// calling the function
something.funny();

因此,当调用 something.funny() 时,我希望发生以下情况:函数 funny 作为闭包在其原始上下文中被调用(例如函数 isBar 和变量 bar 已定义)。因此,当我调用 $.tmpl 时,我希望模板中的 attribute.filter(isBar) 也在此范围内。但事实并非如此。我在 Chrome 中得到 ReferenceError: isBar isBar is not defined
如果有人能如此友好地向我展示我的方法的错误,我会非常高兴。

最佳答案

编辑 糟糕,我错过了“()”。

好吧,问题是那些对闭包中局部变量的引用并不是对局部变量的真正引用——它们是字符串的一部分。模板代码必须解析该字符串,所以当它解析时,在调用“$.tmpl()”的闭包中有一个名为“isBar()”的函数这一事实并不重要; jQuery 无法访问它们,因为您不能在 JavaScript 中这样做。

但是,您可以将“选项”第三个参数传递给“$.tmpl()”并在那里提供额外的内容。我不是 100% 确定如何去做,因为我只玩了一点模板插件,但我会在有机会的时候尝试 jsfiddle。我认为你基本上会做这样的事情:

    funny: function(){
$.tmpl("test", [{"name":"Fo", "attribute":[{"name":"bar", "value":"how"}]},
{"name":"Foo", "attribute":[{"name":"fnord","value":"can"}]},
{"name":"Fooo", "attribute":[{"name":"bar","value":"this"}]},
{"name":"Foooo", "attribute":[{"name":"Bar", "value":"be"}]}
], { isBar: isBar });
}

我不确定您在模板文本中是将其称为“${isBar()}”还是“${item.isBar()}”。

关于javascript - 闭包中的 jquery tmpl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6508950/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com