Search code examples
javascriptjsonhtmlkineticjs

How do I save the stage upon every KineticJS event?


I understand that a KineticJS stage can be saved to JSON with the stage.toJSON function. I would like to perform this action any time the stage changes in any way. For example, I would want to run the toJSON function if a shape was moved via draggable, a shape's size is changed, the inner contents are changed dynamically, a shape is added dynamically, etc. etc. etc. I would really prefer not to specifically listen for all of the possible events and run the same code for each. I would just prefer to capture all events in one call. Is there anything that could help me do this? I realize there could be a performance hit. Saving the stage upon any change being made to it is a business requirement. Fortunately, this functionality is limited to only a few users. Thank you.


Solution

  • How do I save the stage upon every KineticJS event?

    Answer: Call stage.toJSON when any KineticJS event occurs.

    Is there any KineticJS event handler that listens for any-and-all events?

    Answer: Actually, there is one Draconian option.

    You could ask to listen for every event that KineticJS can generate because the .on() method can accept multiple space-delimited event types.

    You would be left with the task of deciding whether to stage.toJSON based on the eventType plus your design considerations.

    Nodes can listen for these event types:

    // a space-delimited list of all node events that KineticJS can listen for
    var allNodeEvents="mouseover mousemove mouseout mouseenter mouseleave mousedown mouseup click dblclick touchstart touchmove touchend tap dbltap dragstart dragmove dragend";
    

    The stage can listen for these event types:

    // a space-delimited list of all stage events that KineticJS can listen for
    var allStageEvents="contentMouseover contentMousemove contentMouseout contentMousedown contentMouseup contentClick contentDblclick contentTouchstart contentTouchmove contentTouchend contentTap contentDblTap";
    

    You can listen for any-and-all Node+Stage events like this:

    // listen for all possible Node events
    node.on(allNodeEvents,function(event){
    
        // get the type of this event
        var eventType=event.type;
    
        // Do stage.toJSON 
        //(or not based on eventType and other design specific considerations
    
    });
    
    
    // listen for all possible Stage events
    stage.on(allStageEvents,function(event){
    
        // get the type of this event
        var eventType=event.type;
    
        // Do stage.toJSON 
        //(or not based on eventType and other design specific considerations
    
    });