function outerFunction0 (someText) {
var outerVar = { option: someText };
if ($("#testId").length <= 0) {
// we bind only at the first call of outerFunction0
$("<span id='testId'></span>").bind("someEvent", function () {
alert(outerVar.option);
}).appendTo("body");
}
$("#testId").text(someText);
}
outerFunction0("add");
$("#testId").trigger("someEvent"); // displays alert("add")
outerFunction0("edit");
$("#testId").trigger("someEvent"); // displays alert("add") too
function outerFunction1 (someText) {
var outerVar = { option: someText };
if ($("#testId1").length > 0) {
$("#testId1").unbind("someEvent1");
} else {
$("<span id='testId1'></span>").appendTo("body");
}
$("#testId1").text(someText);
// bind every time. So the new execution context will be set
$("#testId1").bind("someEvent1", function () {
alert(outerVar.option);
});
}
outerFunction1("add");
$("#testId1").trigger("someEvent1"); // displays alert("add")
outerFunction1("edit");
$("#testId1").trigger("someEvent1"); // displays alert("edit")
function outerFunction2 (someText) {
var outerVar = { option: someText };
if ($("#testId2").length <= 0) {
$("<span id='testId2'></span>").bind("someEvent2", function () {
var myVar = $("#testId2").data("myoptions");
alert(myVar.option);
}).appendTo("body");
}
$("#testId2").text(someText);
// set the options as data of DOM element
$("#testId2").data("myoptions", outerVar);
}
outerFunction2("add");
$("#testId2").trigger("someEvent2"); // displays alert("add")
outerFunction2("edit");
$("#testId2").trigger("someEvent2"); // displays alert("edit")
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.