2012-05-18 48 views
1

我正在嘗試使用jquery對div進行擴展。 的擴展稱爲NunoEstradaViewer,這裏是代碼的樣本:JQuery - 事件處理程序中的acess對象屬性

(function ($){ 

NunoEstradaViwer: { 
    settings: { 
    total: 0, 
    format: "", 
    num: 0; 
    }, 
    init: function (el, options) { 
    if (!el.length) { return false; } 
     this.options = $.extend({}, this.settings, options); 
     this.itemIndex =0; 
     this.container = el; 

     this.total = this.options.total; 
     this.format = ".svg"; 
     this.num = 0; 
    }, 
    generateHtml: function(){ 
    /*GENERATE SOME HTML*/ 

    $("#container").scroll(function(){ 
     this.num++; 
     this.nextImage; 
    }) 
    }, 
    nextImage: function(){ 

    /*DO SOMETHING*/ 

    } 
}); 

我的問題是,我需要訪問的this.num值並調用該函數this.nextImage的處理函數內滾動事件,但對象「this」是指滾動而不是「NunoEstradaViewer」。我怎樣才能訪問這些元素?

謝謝

回答

1

常見的解決辦法是將其存儲到所需的上下文的引用:

(function() { 
    var self; 
    self = this; 
    $('#container').scroll(function() { 
     self.doStuff(); 
    }); 
}()); 

的另一種方法是通過上下文的功能:

(function() { 
    $('#container').scroll({context: this, ..more data to pass..}, function (e) { 
     e.data.context.doStuff(); 
    }); 
    //alternatively, if you're not passing any additional data: 
    $('#container').scroll(this, function (e) { 
     e.data.doStuff(); 
    }); 
}()); 
+0

謝謝您的解答。 。 我設法做這種方式: $( '#集裝箱')綁定( '滾動',{觀衆:這個},函數(事件){ event.data.viewer.num ++; } – Nunoestrada

2

通常我在這種情況下做的是將引用保存到變量中。

generateHtml: function(){ 
    /*GENERATE SOME HTML*/ 

    var self = this; 

    $("#container").scroll(function(){ 
     self.num++; 
     self.nextImage; 
    }) 
} 
相關問題