1

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

2 Answers 2

2

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;
    })
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you for your answers. I managed to do it this way: $('#container').bind('scroll',{viewer: this}, function(event){ event.data.viewer.num++; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.