0

ok I'm not sure if I'm doing this right so if I'm going about it all wrong please explain.

I have a javascript object which is drawing html based on ajax data.

I am then trying to use jquery to handle events on the html output from an instance of the above object. However I would like to call a function and get a property out of the instance of the javascript object which was used to draw the html.

so my code looks something like this:

function obj1 (){
    this.property1 = "propvalue";


    this.dosomething = function () {
        // does some processing
    }

   this.drawhtml = function () {
    // outputs html
   }

}

// jquery to handle events
 $(document).ready(function(){

// .edit is a class in the html outputted from the drawhtml
   $('body').on('click','.edit',function () {
     // call the dosomething from the object
     });

 });

// create instance of object could be multiple on on page
var instance1 = new obj1;

instance1.drawhtml();

Thanks,

4

1 回答 1

3

您可以只使用之前创建的实例:

// jquery to handle events
 $(document).ready(function(){

// .edit is a class in the html outputted from the drawhtml
   $('body').on('click','.edit',function () {
     instance1.dosomething();
     });

 });

// create instance of object could be multiple on on page
var instance1 = new obj1();  // added parentesis so it's valid javascript

instance1.drawhtml();

编辑:从评论开始的附加信息:

处理此问题的最佳方法是将事件处理程序绑定到对象本身。像这样的东西:

function obj1 (){
    this.property1 = "propvalue";


    this.dosomething = function () {
        // does some processing
    }

   this.drawhtml = function () {
       var elem = $("<div>my super dooper HTML</div>");
       elem.on('click', this.dosomething);
   }

}

于 2013-04-18T22:06:03.950 回答