jointjs boundary overflow prevention

example of how to prevent jointjs elements from overflowing their paper

HTML

<link rel="stylesheet" href="http://jointjs.com/css/style.css" />
<link rel="stylesheet" href="http://jointjs.com/css/joint.css" />        
<script src="http://jointjs.com/js/joint.js"></script>

<div id="paper"/>

JavaScript

var graph = new joint.dia.Graph;

var width = 400;
var height = 400;
var gridSize = 1;

var paper = new joint.dia.Paper({
    el: $('#paper'),
    width: width,
    height: height,
    model: graph,
    gridSize: gridSize
});

paper.on('cell:pointermove', function (cellView, evt, x, y) {

    var bbox = cellView.getBBox();
    var constrained = false;
    var constrainedX = x;
    
    if (bbox.x <= 0) { 
        constrainedX = x + gridSize;
        constrained = true
    }
    
    if (bbox.x + bbox.width >= width) { 
        constrainedX = x - gridSize; 
        constrained = true
    }
                        
    var constrainedY = y;
    
    if (bbox.y <= 0) {
        constrainedY = y + gridSize;
        constrained = true
    }
    
    if (bbox.y + bbox.height >= height) { 
        constrainedY = y - gridSize; 
        constrained = true
    }
    
    //if you fire the event all the time you get a stack overflow
    if (constrained) { 
        cellView.pointermove(evt, constrainedX, constrainedY)
    }
});

var actor = new joint.shapes.basic.Rect({
    position: {x:100, y:30},
    attrs: {text: {text: 'drag me off the paper'}},
    size: { height: 92.7051, width: 150}
});

graph.addCell(actor);