2

思路

表格的编辑,即用户对表格的操作,操作表格改变了表格的内容。从代码层面来讲,用户的操作最终都转化成了一个个command,js执行这些command改变了表格内容。因为多个用户的操作就是一个个command的合集,spreadjs提供了anyscLicenser事件来监听用户的操作获取command,用户通过websocket推送拿到别的用户的操作command,执行这些command,那么内容就同步了。

核心代码

因此核心代码如下,可下载文件下来查看效果

        var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
        var spread1 = new GC.Spread.Sheets.Workbook(document.getElementById("ss1"));
        var sheet = spread.getActiveSheet();
        var sheet1 = spread1.getActiveSheet();
        var spreadNS = GC.Spread.Sheets;
        var command = {
            canUndo: true,
            execute: function (context, options, isUndo) {
                var Commands = GC.Spread.Sheets.Commands;
                if (isUndo) {
                    Commands.undoTransaction(context, options);
                    return true;
                } else {
                    Commands.startTransaction(context, options);
                    var sheet = context.getSheetFromName(options.sheetName);
                    var cell = sheet.getCell(options.row, options.col);
                    cell.backColor(options.backColor);
                    Commands.endTransaction(context, options);
                    return true;
                }
            }
        };
        var commandManager = spread.commandManager();
        var commandManager1 = spread1.commandManager();
        commandManager.register("changeBackColor", command);
        commandManager1.register("changeBackColor", command);

        /*添加监听*/
        spread.commandManager().addListener("anyscLicenser",function(){
            for(var i=0;i<arguments.length;i++){
                var cmd = arguments[i].command;
                console.log(cmd)
                if(cmd.clipboardText){
                    cmd.fromSheet = null;
                    cmd.fromRanges = null;
                }
                commandManager1.execute(cmd)
            }
        });
        

all2005
3.4k 声望36 粉丝