user1919
user1919

Reputation: 3938

Issue with passing values in JQUERY functions

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

Answers (2)

kasper Taeymans
kasper Taeymans

Reputation: 7026

A demo will be very handy here:

jsfiddle demo

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

Omri Aharon
Omri Aharon

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);

Fiddle

Upvotes: 1

Related Questions