JSON with function value with parameters

I have very few problems, but I don’t know how to solve it. I need to send 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, I need to pass the func function as a parameter with parameters.

Example:

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

But this does not work :(

Any help with this will be truly appreciated.

+5
source share
4 answers

It's a little incomprehensible what you want, but if you want to define a function that takes parameters, you need something like this:

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

, ? , , :

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

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

Fiddle

+1

You can create a function that closes these arguments:

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

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

Thus, the external function above is called, takes the arguments, and returns a function that uses these original arguments when called.

another_func( jsVariable );

function another_func( obj ) {

    obj.func();  // 7

}

Of course, this has nothing to do with JSON. You cannot serialize any part of the functions.

0
source

Take a look at the JSONfn plugin .

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

He does exactly what you need.

-Vadim

0
source

All Articles