rdarioduarte
rdarioduarte

Reputation: 1999

JSON with function value with parameters

i have a very little problem but don't know how to solve it. I need to send a JSON with a function, but with parameters and this is my problem.

Sending a function in JSON is simple:

var jsonVariable = { var1 : 'value1', var2 : 'value2', func: function(){ alert('something'); } };

I need something else, need to pass the func function as parameter with parameters.

Example:

var jsonVariable = { var1 : 'value1', var2 : 'value2', func: funcParam(param1,param2) };
function(parameter1, parameter2){
     alert(parameter1 + parameter2);
}

But this don't work :(

Any help with this will be really appreaciated

Upvotes: 5

Views: 8993

Answers (4)

vadimk
vadimk

Reputation: 1471

Take a look at the JSONfn plugin.

http://www.eslinstructor.net/jsonfn/

It does exactly what you need.

-Vadim

Upvotes: 0

RightSaidFred
RightSaidFred

Reputation: 11327

You can create a function that has closed over those arguments:

var send_func = (function( param1, param2 ) {
    return function(){
        alert(param1 + param2);
    };
}( 3, 4 ));

var jsVariable = { var1 : 'value1', var2 : 'value2', func: send_func };

So the outer function above is invoked, receives the arguments, and returns a function that when invoked uses those original arguments.

another_func( jsVariable );

function another_func( obj ) {

    obj.func();  // 7

}

Of course this has nothing to do with JSON. You won't be able to serialize any part of the functions.

Upvotes: 0

Jordan Wallwork
Jordan Wallwork

Reputation: 3114

Are you looking to be able to pass any number of parameters to the function? If so, try passing an array to your function and iterate through, eg:

var jsonVariable = {
    var1 : 'value1',
    var2 : 'value2',
    func: function(params){
        var alertString = "";
        for (var i = 0; i < params.length; i++)
            alertString+=params[i]+" ";
        alert(alertString);
    }
};

and call it using

jsonVariable.func(["param1", "param2"]);

Fiddle

Upvotes: 1

Matt
Matt

Reputation: 75307

It's a bit unclear what you want, but if you want to define a function which accepts parameters, you'll want something like this;

var jsonVariable = { var1 : 'value1', var2 : 'value2', func: function(param1, param2){ alert(param1 + param2); } };

Upvotes: 1

Related Questions