Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a Backbone.js click event to a view rendered inside a HTML5 canvas?

I am just getting started with Backbone.js, but it looks really interesting...

Right now, I am redoing a previous project that draws various objects (2-3 different model types) into a single HTML5 canvas.

Each object is clickable. There is a event handler for the canvas that gets the location of the click (local to the canvas object) and then searches the objects for one that could produce a hit.

Is there a particular way or best practice that I should use when doing this for a click event on a Backbone.js view?

Thanks!

Update: found fabric.js which seems to handle the idea of objects within a canvas element, but doesn't provide the MVC style framework as backbone.js.

Also, I took a look at knockout.js. It seems even more tied to HTML elements (not canvas) than backbone.js.

like image 602
Chris Butler Avatar asked Apr 15 '11 06:04

Chris Butler


People also ask

Why use Backbone js?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

What is backbone in programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

I came across this question because I'm working on a Backbone-based framework for working with canvas, so I grappled with this myself. The answer I eventually came to was: Forget about using Backbone.View with canvas. If it can't be represented by a DOM element, then it doesn't make sense to use Backbone.View for it; its properties just don't map to canvas "elements."

You could use Backbone.View to represent a single canvas DOM element just fine, mind you, but that's not the scenario you're describing. What you need is a custom view class that can represent your in-canvas objects and handle their events.

like image 134
Trevor Burnham Avatar answered Nov 02 '22 23:11

Trevor Burnham