I have the following simple code:
var tabs = null;
function addTab(id, title, data) {
alert("Begin: " + data.name);
if (tabs === null) {
tabs = $("#center-tabs").tabs({
tabTemplate: "<li style='line-height: 0.5'><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
add: function (event, ui) {
alert("Event: " + data.name);
}
});
}
tabs.tabs("add", id, title);
tabs.tabs("select", id);
}
When I call:
addTab(“#tab-1”, “Tab-1”, {
name: “Example 1”
});
two alerts are displayed (“Begin: Example-1” and “Event: Example-1”)
But if I call again:
addTab(“#tab-2”, “Tab-2”, {
name: “Example-2”
});
two alerts are displayed but first one with correct message and second with the message of the first call (“Begin: Example-2” but “Event: Example-1”)
What I’m doing wrong?
Is it a tabs implementation bug?
Thanks in advance
No, it is not a bug.
First time you call
addTab()variabletabsisnullso the body of if-statement is executed. Inside the if you defineaddmethod with a body works withdata.name(Example 1). This is expected.The problem is that during the 1st run a closure is created that contains the
datavariable withExample 1value. When you call youraddTab()2nd timetabsis already created and inside theaddmethoddata.nameis still referring to the olddata.namewhich got saved during the 1st run. Youralert()cannot see the new value of thedata.See http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/ .
You can solve it by not accessing
addTabsvariables/parameters insideadddirectly because that will “save them” into a closure, but using other mechanism such as jQuery’s .data().HERE is an example.