简体   繁体   中英

socket.io rich text editing with Quill

I was trying to implement Quill API with socket.io to build a realtime editor. I was able to get the Delta emitted, but quill.updateContents() does not seems to update the text editor with the emitted Delta op data.

Here is my code:

index.html (client side)

    <!DOCTYPE html>
<html>
<head>
    <title>Connected Clients</title>
    <!--<meta charset="UTF-8"> -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <!--<script type="text/javascript" src="jquery.js"></script>  -->
    <script src="/socket.io/socket.io.js"></script>
    <link href="https://cdn.quilljs.com/1.1.1/quill.snow.css" rel="stylesheet">
    <link href="https://cdn.quilljs.com/1.1.2/quill.snow.css" rel="stylesheet">
</head>

<body>
    <div id="editor">
    <p>Hello World!</p>
    <p>Some initial <strong>bold</strong> text</p>
    <p><br></p>
    </div>

    <span id="insertHere"></span>

    <script src="https://cdn.quilljs.com/1.1.2/quill.js"></script>
    <script>
        $(document).ready(function () {
        var quill = new Quill('#editor', {
            theme: 'snow'
        });

        var socket = io();
        socket.on('updated_para',function(data){
            var el = document.getElementById('insertHere');
            el.innerHTML = data;
            var ops = data;
            quill.updateContents(data);
        });

        quill.on('text-change', function(delta, source)  {
            var para = quill.getContents();
            socket.emit('para',{delta:JSON.stringify(delta.ops)});
        });
    });  
    </script>
</body>
</html>

index.js (server side)

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});


http.listen(3000, function(){
    console.log('listening on *:3000');
});

io.sockets.on('connection', function(socket){
    console.log('a user connected');

    socket.on('disconnect', function(){
        console.log('user disconnected');
    });

    socket.on('para',function(data){
        io.emit('updated_para',data.delta);
        console.log('message: ' + data.delta);
    });
});

I will really appreciate your help!

i think you forget to convert the json code back to an object.. you convert the data before sending to your socket server to a json string. So the date you receive would alway be a string instead of an json.object.

// Replace

var ops = data;
quill.updateContents(data);

// with 

var ops = JSON.parse(data);
quill.updateContents(data);

i'm planning to make a similar kind of editor, so i can watch / share code editing.

Kind Regard.

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