简体   繁体   中英

Change JavaScript object values with auto-generated HTML form

I have got a 'big' JavaScript object that looks somewhat like this:

var userConfig =  {   
      active: true,  
      subElement: { someProp: 156, otherProp: 'yaye' },  
      foo: ['bar', 'see', 'no']  
      // etc  
}

What I'm looking for is some sort of framework that I pass the variable (or a part of the variable) to and that reads all properties and creates a form where these can be configured. So a checkbox would be created for a boolean, a textbox for a string etc...

Anyone knows about such a library?

Update : At the moment settings are changed by opening the JS and editting the variables manually (The JS is a locally stored greasemonkey script). Pretty much anything beats that really.
I'm not interested in writing (alot of) code to do two way binding, creating all the UI widgets and having a clean seperation of concerns (MVVM, MVP, ...) which is what Knockout/Backbone/... does (judging from the tutorials).

Instead :

var userConfigUpdater = {
    active: { description: "Activates or deactivates feature X", editType: "boolean"},
    subElement: {
        description: "subElement",
        editType: "tabularItem",
        someProp: {description: "foo", editType: "text"},
        // more
    }
}
createHtmlWidgets(userConfig, userConfigUpdater);

Now the user can edit the form elements and then we have something like: $("#okButton").click(function() {userConfig = getUpdatedValues();});

Granted, it doesn't look very nice, but it would get the job done quite fast/easily. I'm guessing there is not yet some public framework that does something like this?

The closest thing I know is knockoutjs. This doesn't do exactly what you want but what it does do is allow a mechanism for keeping that object in the knockout world it would be called a viewModel in sync with your form so if you update the form contents it would update that object's data automatically and vice-versa

I ended up writing my own 'framework'.

It is 'pretty' generic but somewhat integrated into the rest of my project, really limited in features and the API is not very clean. Use at your own risk :)

The source code on GitHub . The 'framework' is propui.js and sangu_config.js is the configuration for propui.

Example how to call the API:

backgroundColor: {
    label: "Change the background color",
    propUI: {
        getter: function() { return settings.backgroundColor; },
        setter: function(value) { settings.backgroundColor = value; },
        editor: "bool"
    }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM