私はこの小さなJavaScriptライブラリと様々な提案に従っています。さまざまな理由(変数のカプセル化、コードの隠蔽など)のためにクロージャで自分の機能をラッピングしています。私はJSON Webサービスを照会し、結果を表示するので、jquery tmplエンジンも使用します。
私は閉鎖が良いものであることを理解していると思いますが、一般的にそれらを理解していません。私はすべてのそれらのスコープの変更とそれ以外のものとの間で完全に失われることを意味します。特に迷惑なのは、この例外です。次のコードを考える(問題のコードの簡素化醜いバージョンを、それは、問題を再現)something.funny()
を呼び出すときに、私は次のことが起こることを期待するのでjquery tmpl in closure
// 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();
を:機能funny
を、閉鎖されて呼び出されます(例えば、関数isBar
と変数bar
が定義されています)。だから私が$.tmpl
と呼ぶと、テンプレート内のattribute.filter(isBar)
もこのスコープに入ると思った。しかし、そうではありません。私はクロム私はReferenceError: isBar is not defined
を取得します。
誰かが私のやり方の誤りを私に示すことがとてもうれしいなら、私はとても幸せになるでしょう。
はいそれです。私は '{isBar:function(data){return data.name ===" bar ";}'をオプションパラメータとして渡し、テンプレート内の '$ {$ item.isBar()} 'を参照することができました。 ありがとう! – Jan