Question

I have a config, and in it I want to determine a function to be used in some code later:

get_config = () ->
    {
        "function" : (stuff) ->
            stuff + "more stuff"
    }

This code is called somewhere, and the config is stored as json in a file, using the following helper function:

stringifyWithFunctions = (object, replacer, spacing) ->
    stringify_functions = (key, val) ->
        if replacer
            if typeof val == 'function'
                return replacer(key, val.toString())
            else
                return replacer(key, val)
        else
            if typeof val == 'function'
                return val.toString()
            else
                return val

    return JSON.stringify(object, stringify_functions, spacing)

I end up with a json object that looks like this:

{ 'function' : 'function (stuff) {return stuff + "more stuff"}' }

However, I can't figure out a good way to load this function later.

loaded_function = eval(config['function'])

Results in an error "Unexpected token (" and I feel as if there's likely a cleaner way of doing this. Any ideas?

Était-ce utile?

La solution

If the config JSON is stored as a static file and used over and over, a clean solution would be to simply remove the quotes from around the function(s) in the JSON and then do this:

var get_config = eval("(" + json_data + ")");

The JSON needs to be wrapped in parenthesis to evaluate, that's why you're getting the error. If the config JSON is constantly needing to be stringified then there's a couple of other options. You could do this to call the function:

var get_config = eval("(" + json_data + ")");

eval("(" + get_config.afunction + ")")("this is passed to the function");

or you can use the JSONfn plugin (http://www.eslinstructor.net/jsonfn/) to stringify the JSON instead of the functions you're using and just eval it like above. The JSONfn plugin is able to serialize functions like you're needing to do.

Here's a jsFiddle to mess with that shows the above code in use: http://jsfiddle.net/4UP53/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top