0

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?

3
  • 2
    Do you have a question? Is there a problem with your code? Commented Jun 24, 2016 at 5:55
  • i think you have a problem accessing the ObjHandler(el) within subObjs.each. To overcome that issue; just create var self = this; at first line in this.init() { function and then use that variable inside .each( like el = new self.ObjHandler(el). Commented Jun 24, 2016 at 6:06
  • So it is good idea? i try it but it doesnt work can you show me how to do it? codepen.io/Messa/pen/XKpXQZ?editors=0011 Commented Jun 24, 2016 at 6:19

1 Answer 1

1
  • 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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you, now i see it and learn something new i just have a idea but don know ho to do it right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.