Skip to content Skip to sidebar Skip to footer

Js Objects Attached To Html Elements

I've been getting more into oop with js (I'm classically trained in Java) and I have four boxes. I want to do something like this:
<\div>

Solution 1:

Here is a fiddle explaining what u want achieve. https://jsfiddle.net/2e24a3kx/

First, you need to find all boxes. Then for every box, create new box, pass a reference to DOM object, and connect handler.

var boxes = $.find('.box');
   for(var i = 0; i < boxes.length;  i++) {
       var box = newBox();
       box.$view = $(boxes[i]);
       box.connectClick();
   }

Count is "private variable". It is created as local scope variable at calling function Box. Box function "remembers" all local scope variables. With creation of object with new, you need functions created locally (this.increateCounter) so they have access to count variable. With getCounter / increaseCounter functions in Box, you have access to counter.

In function connectClick im passing to jQuery variable a function with binded (this). Beacuse this is our object - box. While jquery at connecting handlers change this variable to DOM. Function Bind changes function this variable to our Box, bind returns new function. https://www.google.pl/search?q=mdn+Bind&oq=mdn+Bind&aqs=chrome..69i57j69i60j69i59j69i61j69i59l2.1082j0j7&sourceid=chrome&es_sm=93&ie=UTF-8

functionBox(){
       //PRIVATE VARthis.$view;
       this.increaseCounter = function () {
           count++;
       };

       this.getCounter = function () {
           return count;
       }
        var count=0;
   }

Jquery is diffrent, not simpler. Its just more structural way. While you model it in OOP u have to do a little more effort to maintain some structure.

I think the best pattern is to use pure JavaScript function addEventListener(event, object),

where you can directly pass as object Box. Box have then implement function onEventReceived (event)

http://www.thecssninja.com/javascript/handleevent

Post a Comment for "Js Objects Attached To Html Elements"