简体   繁体   中英

JQuery - acess object property inside event handler

I am trying to do an extension to a div using jquery. The extension is called NunoEstradaViewer, and here is a sample of the code:

(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*/

  }
});

My problem is that I need to access the value of this.num and call the function this.nextImage inside the handler function for the scroll event, but the object "this" refers to the scroll and not to the "NunoEstradaViewer". How can I access those elements?

Thank you

Usually what I do in this case is to save the reference to "this" in a variable.

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

    var self = this;

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

The common solution is to store a reference to the desired context:

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

An alternative method is to pass the context to the function:

(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();
    });
}());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM