1. Description of the task
Developing a large mind map application, we chose
Backbone as the main library for building an application. In this case, the mind map is drawn through the canvas element with the help of various primitives. We chose the
KineticJS library to work with the canvas, as it perfectly supports working with events for objects on the canvas.
To comply with the Backbone architecture, all work with canvas (more precisely with instances of KineticJS objects) occurred in Backbone.View instances:
var Node = Backbone.View.extend({ initialize : function(params) { this.layer = params.layer; this.node = this.el(); this.bindEvents(); }, el : function(){ var rect = new Kinetic.Rect({ x : 100, y : 100, width : 50, height : 50, fill : 'green', id : 'rect' }); return rect; }, bindEvents: function() { this.node.on('click', function(){ console.log("on rectangle clicked"); }
')
2. The problem
But Backbone View was designed to work with DOM elements, and with this approach, we did not generate div objects that we needed and declare events in declarative style (
http://backbonejs.org/#View-delegateEvents ) did not work either.
3. Solution.
The
Backbone.KineticView plugin was written, which allowed working with objects on canvas (through KineticJS) in the same style as the usual Backbone.View works with the DOM.
An example of how the code now looks:
var MyView = Backbone.KineticView.extend({ initialize : function(params) { this.layer = params.layer; }, nodeType : 'Rect', attributes : { x : 100, y : 100, width : 50, height : 50, fill : 'green', id : 'rect' },
This plugin almost repeats the functionality of Backbone.View, but only for KineticJS objects. By analogy, tests from Backbone.View were adapted.
A slightly more complex live example can be found here:
http://jsbin.com/fekex/4/editPlugin code:
https://github.com/slash-system/backbone.kineticviewProbably similar solutions can be easily built for similar canvas libraries:
Easeljs ,
FabricJS , etc. Has anyone already solved this problem?