2014-07-14 18 views
2

我有一個自己的js類,並嘗試在點擊事件中使用jquery的$(this)和object-this。

jquery's $(this)work fine,but the object-this is not defined。

http://jsfiddle.net/j33Fx/2/

var myclass = function(){ 

    this.myfunction = function(){ 
     alert('myfunction'); 
    } 

    this.buttonclicked = function(){ 
     alert('buttonclicked'); 
    } 

    this.writeout = function(){ 
     var buttoncode = '<button class="mybutton">click</button>'; 
     $('body').append(buttoncode); 

     $('.mybutton').click(function(){ 
      alert('Button: '+$(this).attr('class')); 
      this.buttonclicked(); 
     }); 

     this.myfunction(); 
    } 

} 


var x = new myclass(); 
x.writeout(); 

當我點擊按鈕追加,我得到了按鈕的類名的警告,但我的功能「this.buttonclicked」似乎不是一個功能。

任何想法?

回答

9

this引用調用事件處理程序中的事件的元素。您可以將當前對象緩存在其他一些變量中。哪些可以用於後者。

使用

this.writeout = function(){ 
    var buttoncode = '<button class="mybutton">click</button>'; 
    $('body').append(buttoncode); 

    var _self = this; //cache current object 

    $('.mybutton').click(function(){ 
     alert('Button: '+ $(this).attr('class')); //Here this refers to element which invoked the event. 

     _self.buttonclicked(); //Use cached object 
    }); 

    this.myfunction(); 
} 

Updated Fiddle

+0

是有解決這個時傳遞到點擊()回調函數是一個更大的otherClass物體的方法,它使用的方式「這個」內部試圖指其他類? –

+1

@JoseOspina,我不知道你確切的問題,但你可以看看[Function.prototype.bind()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/ Global_objects/Function/bind) – Satpal

+0

太棒了!現在我只需重構我的所有應用程序!好好玩!謝謝! (我的意思是,真的:我正在做一些醜陋的東西來克服這個......謝謝) –