问题
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 class="box"><\div>
<div class="box"><\div>
<div class="box"><\div>
<div class="box"><\div>
Function Box(){
//PRIVATE VAR
var count=0;
}
Box.prototype.move = function(){
this.css({left:50});
}
Box.prototype.click= function(){
this.count++;
}
//create new instances of box and assign or connect to the four HTML elements
For (var i = 0; i < $('.box').length; i++){
$('.box')[i] = new Box();
}
Basically I want each box to have its own private click count property that gets incremented each time it gets clicked.
Is this a desirable pattern or is it a poor practice to connect an HTML element like this? Should I be passing HTML elements to the functions instead? And if so, how would I keep an objects private click var in-sync with a specific element.
I obviously know there are simpler jQuery ways to do this but I want to focus on oop.
回答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 = new Box();
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
function Box(){
//PRIVATE VAR
this.$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
来源:https://stackoverflow.com/questions/31540797/js-objects-attached-to-html-elements