Saving settings back to the server
-
In the documentation, the Setting example mentions doing: socket.emit('admin.settings.syncMyPlugin');".
I am guessing it requires me to implement some code on the back-end. Can anyone shed some light on how to save back to the settings? Isn't just a matter of setting it and syncing it? Why the socket operation?
-
The settings page could a bit of editing, it took me quite a while to understand everything that's happening.
On the server, you load the settings with something like:
var Settings = module.parent.require('./settings'); var mySettings = new Settings('myPlugin', '0.1', defaultSettings, function(){ console.log(mySettings.get('somesetting')); });
This will load the settings from the database into the mySettings object, but will not update them after they change.
To update the the mySettings object, you have to do sync:
mySettings.sync(function () { console.log(mySettings.get('somesetting')); // Updated });
Now on the client, when you do settings.persist(), the new settings are saved to the database, but the mySettings object on the server is not updated, so we need do a socket.emit() to let the server know that it needs to sync the mySettings object.
// Client admin page require(['settings'], function (settings) { var wrapper = $('#my_form_id'); // This loads the data from the database to the DOM. settings.sync('myPlugin', wrapper); $('#save').click(function(event) { event.preventDefault(); // This saves the settings from the DOM to the database. settings.persist('myPlugin', wrapper, function(){ // When we're done saving to the database, send a socket event to server so it can update it's mySettings object with the new values. socket.emit('admin.settings.syncMyPlugin'); }); }); });
// On the server var SocketAdmin = module.parent.require('./socket.io/admin'); // Socket event exposed to the client as 'admin.settings.syncMyPlugin' // It gets called when the client saves new settings to the database. SocketAdmin.settings.syncMyPlugin = function() { mySettings.sync(function () { // The mySettings object is updated, you can now call whatever functions you want to based on the new values. if (mySettings.get('somesetting') === 'justDoIt') doThing(); }); };