Robert Limanto Robert Limanto - 3 months ago 9
Javascript Question

Object oriented javascript for event handling

Hi i tried to modularize my javascript and make it object oriented, but i got confused when i tried to do it with component with multiple instances.

My code looks like this

HTML file

<div id="1" class="home-post-list" data-id="1">
<div class="home-post-list-hide">
</div>
</div>
<div id="2" class="home-post-list" data-id="2">
<div class="home-post-list-hide">
</div>

</div>


The HTML ids above (#1, #2) are randomly generated from the server.

This is the code currently (NOT OOP),

$(document).on('click', '.home-post-list', function(e){
var id = $(this).data('id');
var $widget = $("#" + id);
$widget.find('.home-post-list-hide').hide();
});

$(document).on('mouseover', '.home-post-list', function(e) {
var id = $(this).data('id');
var $widget = $("#" + id);
$widget.find('.home-post-list-hide').show();
});


I want to make something like this.

var HomePostList = function(){
this.$widget = this.find('.home-post-list-hide');
this.init();
};

HomePostList.prototype.init() {
//event handling
}


the reason i want to make it OOP, because i want to make communication between components and i don't have to rewrite $widget.find('.home-post-list-hide').hide() many times.

Answer

You can do it like this.

var HomePostList = function($root){
    this.$root = $root;
    this.$widget = this.$root.find('.home-post-list-hide');
    this.init();
};

HomePostList.prototype.init() {
    //event handling
}


list = []
$(".home-post-list").each(function(el){
    list.push(HomePostList($(el)));
});