francisco.preller
francisco.preller

Reputation: 6629

Storing Javascript object with functions in an SQL database

I am developing a javascript menu (using jQuery).

As an example, the below is the structure of the items object I would pass to my custom function which then creates the menu.

var items = {
    0: {
        name: 'file',
        submenu: {
            0: {
                name: 'open',
                hasSubitems: true,
                subitems: {
                    0: {
                        name: 'file',
                        hasSubitems: false,
                        callback: function() { alert('you opened a file!'); }
                    },
                    1: {
                        name: 'project'
                        hasSubitems: false,
                        callback: function() { alert('you opened a project!'); }
                    }
                }
            },
            1: {
                name: 'exit',
                hasSubitems: false,
                callback: function() { alert('you logged out!'); }
            }
        }
    },
    1: {
        name: 'edit',
        submenu: {
           ...
        }
    }
}

I would like to be able to store the above into a database, including their prospective callbacks. I intend to create an interface to build the menus dynamically and such.

I realize I could create a JSON string and store it that way, but then what about the callback functions? I have been recommended against using eval several times, so in what other ways might people safely store this information in a database so it can be called upon later?

Upvotes: 0

Views: 2705

Answers (1)

Jake Feasel
Jake Feasel

Reputation: 16955

JSON is language neutral (despite the name), and as such it only supports primitive values. Callback functions are language specific (javascript in this case), and so they cannot be included in anything that needs to be interpreted as pure JSON.

I recommend pulling your callback code out of here, and instead include necessary parameters that you would need to distinguish each one. Then, run this JSON object through a JS template engine (like Handlebars.js) with helper functions rather than your callbacks. These can be invoked with the parameters you used to replace your callback functions in your (now valid) JSON object.

Upvotes: 1

Related Questions