I'm trying to create a little jQueryUI plugin that allows the user to draw rectangles on a div#canvas. The plugin extends ui.mouse and takes care of appending a helper, to visualize the process of drawing the rectangle, but it doesn't actually render it.
Instead, it should return a boxProperties object, but I haven't been able to do that.
I'm fairly new to IIFEs and haven't fully grasped closures but I suspect that the solution lies somewhere there. I've tried some stuff but in lack of proper knowledge couldn't achieve anything.
The catch is that div#canvas (where the rectangles are drawn), is actually a Marionette.CollectionView and the rectangles themselves are going to be Marionette.ItemView added dynamically to the collectionview, which will render them as soon as they're drawn.
What should I add to my code, so that as soon as a rectangle is drawn, a boxProperties object is returned so that I can pass it to the rectangle ItemView in order to get it rendered?
Here's my plugin code
(function($, undefined){
$.widget('nc.boxMaker', $.ui.mouse, {
version: '0.0.1',
options: {
distance: 60
},
_create: function() {
el = this.element;
screenOffset = el.offset();
screenOffset.left = Math.round(screenOffset.left);
screenOffset.top = Math.round(screenOffset.top);
this._mouseInit();
},
_mouseStart: function(event) {
this.coords = [event.pageX - screenOffset.left, event.pageY - screenOffset.top];
this.boxHelper = $(document.createElement('div'));
this.boxHelper.css({
"border":'1px dotted black',
"z-index": 100,
"position": "absolute",
"left": this.coords[0],
"top": this.coords[1],
"width": 10,
"height": 10
});
el.append(this.boxHelper);
},
_mouseDrag: function(event) {
var x1 = this.coords[0], y1 = this.coords[1],
x2 = event.pageX - screenOffset.left, y2 = event.pageY - screenOffset.top;
if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; }
if (y1 > y2) { var tmp1 = y2; y2 = y1; y1 = tmp1; }
boxProperties = {left: x1, top: y1, width: x2-x1, height: y2-y1};
this.boxHelper.css(boxProperties);
},
_mouseStop: function(event) {
this.boxHelper.remove();
return boxProperties;
}
});
})(jQuery);