I have been severely bitten by Javascript’s closures bug a few days ago, but was too busy to ask. I am trying something like the following with the jQuery template engine.
<ul id="container"></ul>
<script type="text/jq-tmpl" id="myTmpl">
<li>
<span style="background:#fafafa">X:${X}</span>
<span style="background:#ababab">Y:${Inner.Y}</span>
<span style="background:#9a9a9a">Z:${Inner.Z}</span>
</li>
</script>
function OuterObject(x,y,z){
this.X = x;
this.Inner = InnerObject(y,z);
}
function InnerObject(y,z){
this.Y=y;
this.Z=z;
}
$(function(){
var l=[];
l.push(OuterObject(1,"One","inner-1"));
l.push(OuterObject(2,"Two","inner-2"));
$("#myTmpl").tmpl(l).appendTo("#container");
});
The problem is that it shows inner-2 and Two for both the items rendered. I have also tried it like this:
var a=OuterObject(1,"One","inner-1");
l.push(a);
var b=OuterObject(2,"Two","inner-2");
l.push(b);
But is all the same.
It looks like you need to use ‘new’ when calling your constructor functions.
e.g.
new Outerobject(...)andnew InnerObject(...)Otherwise, the
thisobject won’t be returned.