Note that there are some explanatory texts on larger screens.

plurals
  1. POOO Javascript - Events
    text
    copied!<p>I'm trying to learn JavaScript, using an OO approach. This is my code:</p> <pre><code>/*global document, MouseEvent */ MouseEvent.prototype.mouseCoordinates = function () { return { 'x' : this.pageX - this.target.offsetLeft, 'y' : this.pageY - this.target.offsetTop }; }; (function () { var Pencil = function () {}, Canvas = function () { this.element = document.getElementById('canvas'); this.tool = new Pencil(); this.element.addEventListener('click', this.tool.draw, false); }, c; Pencil.prototype.draw = function (event) { var context = event.target.getContext('2d'), coordinates = event.mouseCoordinates(); context.fillRect(coordinates.x, coordinates.y, 5, 5); }; c = new Canvas(); }()); </code></pre> <p>I'm trying to do something like MS Paint. So, I've created a Canvas object and a Pencil one. I am able to do it using a procedural approach but I don't want to. I don't want to use any library now, I'm just studying.</p> <p>I've these questions:</p> <ul> <li><p>Are there any good practice to register events? Should I register events using the object constructor?</p></li> <li><p>My canvas object has a tool (pencil in this case) object. Conceptually it's not good. My canvas should not have a tool object. It must provides a surface to draw and that's it! But, it's there as a callback (click event). How could I solve this?</p></li> <li><p>Every tool will have the same interface but different behaviours. Could I create interfaces using Javascript?</p></li> <li><p>What else can I improve?</p></li> </ul> <p>UPDATE:</p> <pre><code>(function () { var pencil = { draw : function (event) { var context = event.target.getContext('2d'), coordinates = event.mouseCoordinates(); context.fillRect(coordinates.x, coordinates.y, 5, 5); } }, currentTool = pencil, canvas = (function () { var object = {}; object.element = document.getElementById('canvas'); object.element.addEventListener('click', function (event) { currentTool.draw(event); }, false); return object; }()); }()); </code></pre> <p>I've followed all the tips (thank you, I appreciate your help!). What do you think? Now I have a "global" currentTool variable. What do you think about it? Thanks.</p> <p>Thank you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload