JQuery plugin: get the "this" object inside other functions

I am trying to create a panorama slider as a jQuery plugin and I have the following code.

 $.fn.panorama = function(settings) {

    var myPanorama = this;
    ..

    this.mousedown(function(e){

       //do stuff 
       $(this).css... //this all work
    }


    //Call mouseup on document in case user lets go of mouse outside draggable object
 $(document).mouseup(function(){
    $(myPanorama).easeDragging(); //works but probably not the way to do it
       this.easeDragging(); //ideal but refers to wrong object
 });

    }

My question is, how can I refer to the "this" object inside the call to $ (document) .mouseup?

Because he believes that “this” is the document itself, not the object attached to the plugin.

For now, I'm just making a variable, and it works, but there must be a better way!

thank!

+5
source share
3 answers

Actually, the way you reached it is the easiest way to do this: keep a link to this:

var myPanorama = this;

// ...

    myPanorama.easeDragging();

jQuery.proxy(), ( @Nick):

$(document).mouseup($.proxy(function(){
    this.easeDragging(); 
}, this));

- ECMAScript 5th edition.bind(), , :

// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}

:

$(document).mouseup((function(){
    this.easeDragging(); 
}).bind(this));
+7

, , ( ).

, , jQuery, :

myPanorama.easeDragging();
+2

( ), , ( ).

, , .

$(document).bind('mouseup.panorama', function() {
    ...
}
0
source

All Articles