0

I'm building a neat texteditor in Electron and want to autosave everything that has been typed in <div id="editor" contenteditable="true">. How can this be done?

At the moment, the saving-stuff works with the click of a button, which is reasonably simple:

document.getElementById("saveChanges").onclick = function() { }

I tried to change the above line to this:

document.addEventListener('keydown', function(e) {
    for (var i = 0; i < editor.length; i++)

This doesn't work, but I've also no clue as to why not. It doesn't give any errors, but also doesn't do anything.

What am I doing wrong?

// This is the code that doesn't work

document.addEventListener('keydown', function(e) {
    for (var i = 0; i < editor.length; i++)
    {
        let content = document.getElementById("editor").innerHTML;

        console.log(content);

        const sqlite3 = require('sqlite3').verbose();

        let db = new sqlite3.Database('./appdata/resources/protodatabase.evv');

        let sql = 'UPDATE Subchapters SET subtext=? WHERE subid=1';

        db.run(sql, content, function (err) {
            console.log();
            if (err) {
            return console.error(err.message);
        }});

    db.close();
    };
    });
  • I am guessing that you are using node.js. In that case what you are doing completely wrong. node.js only runs on your server. You can only open a connection to a database using node.js, not regular js. You cannot connect to a database client-side. – Wendelin May 04 '19 at 22:13
  • Thx for your quick reply :) I have no need for client-side database connection, since it's a local Electron-app I'm building. The database is stored on the local disk and I can access is through regular javascript. It works :) – Anderverhaal May 05 '19 at 09:28
  • Oh, sure if you are building an electron app than this will work of course. – Wendelin May 05 '19 at 13:18

1 Answers1

0

I actually figured it out myself:

var editable = document.getElementById('editor');
editable.addEventListener('keydown', function(e) {
    // execute code when spacebar or enter is pressed
    var toets = e.keyCode;
    if (toets == 32 || toets == 13)

This works pretty well. But the code is very, very disk-intensive. Need to figure out how to put the database in memory, do all the changes there and save it periodically to the database on the disk...

  • You could either [debounce](https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript) the keydown event, or save all changes to an Object with key-value-pairs and periodically (e.g. via `setInterval) query your db with an update from that data. – Constantin Groß May 05 '19 at 09:40
  • Thx, I'm going to check it out :) – Anderverhaal May 05 '19 at 14:20