Holoch Messa Holoch Messa - 5 months ago 12
jQuery Question

create object in object JavaScript

Hi i have object which has container element and same subElement:

var Obj = function(){
this.container = $('.obj');
this.subObjs = container.find('.subObj');
}


In this Obj i want create another Object(ObjHandler) who ad handlerOn click for each sub object.

var Obj = function(){
this.container = $('.obj');
this.subObjs = container.find('.subObj');

this.init = function() {
this.subObjs.each(function(i,el){
el = new this.ObjHandler(el)
});
}

this.ObjHandler = function(element) {
this.el = element;
this.element.on('click',function(){
console.log('click');
});
}

}


I know i cam make it simple way like
this.subObjs.on('click', function(){})

but i this is only simplification.

here is on codepen.io

Is it good idea and why its no works?

Answer
  • this.element is not defined use either this.el or element
  • element is an instance of the native JS Element. Wrap it with $() to get a jQuery object that defines the on function
  • You never create an instance of Obj or call init

fixed pen