Reputation: 3938
With some help I have written in JQUERY this:
$('id').clickToggle(addMarker, destroyMarker);
where clickToggle is a function which calls addMarker and destroyMarker functions.
This is the clickToggle() function:
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
And addMarker() function is
var addMarker = function(){ ....}
I don't have so much xp in JQUERY. What I want to do is to pass a variable inside the addMarker() function. The way my code is written how can I do it?
Upvotes: 1
Views: 46
Reputation: 7026
A demo will be very handy here:
HTML
<div id="myid">click me</div>
Javascript/jquery
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
//lets pass the strings "world" and "foo" to addMarker and destroyMarker
$('#myid').clickToggle(function(){addMarker("world")}, function(){destroyMarker("foo")});
//pass a variable as a parameter to the functions
var addMarker = function(x){ alert("addmarker "+x)}
var destroyMarker= function(x){alert("removemarker "+x)}
Upvotes: 1
Reputation: 17064
If you're using a global variable, you can do it like this:
var x = 5;
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
funcs[tc].call(this, x);
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
$('id').clickToggle(addMarker, destroyMarker);
Upvotes: 1