2012-05-18 49 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; 
    }) 
} 
相关问题