jQuery plugin, context and setTimeout

与世无争的帅哥 提交于 2019-12-11 08:49:16

问题


I'm writing a plugin for jQuery and I have a mess in my head with the context issue in javascript.

This is a simplified version of my plugin:

(function($){  

$.fn.myplugin = function(options){
    return new MyPlugin(this, options);
};


function MyPlugin(el, o )
{
    this.root    = el;
    this.input_box = el.find('#the_input');
    this.map = null;
    this.timeout = null;
    var self = this;

    self.input_box.keyup( function(){
    if( self.timeout!==null )
    {
       clearTimeout( self.timeout );
    }
    self.timeout = setTimeout( function(){
            self.search_address( self );
            }, 500 );
    });
}

MyPlugin.prototype = {

    search_address : function( context ){
          geocoder.geocode({'address':$('#direction').val()}, 
             function( results, status ){
              var lat = results[0].geometry.location.lat();
              var lng = results[0].geometry.location.lng();
              var latlng = new google.maps.LatLng( lat, lng );

              context.select_address( latlng, '' );                                   
    },

    select_address : function( latlng, text ){
        self.root.find('#url').val('http://maps.google.com/?q='+encodeURI($('#direccion').val())+'&ll='+coords.lat()+','+coords.lng()+'&ie=UTF8&oe=UTF8&z=18');
    }
};
})(jQuery);

I've read that setTimeout sets the context to the global object, so I did the closure to be able to pass the context to search_address function. This allowed me to call select_address from the callback in geocode function, but this callback is calling select_address and there the context is again undesired: self.root is not found.

I'm completly lost at how to handle the context, I though that using the var self=this at the initialization of the "object" I would avoid these problems...

I must note that select_address can be called directly...


回答1:


Use this at that point to refer to the current context:

select_address : function( latlng, text ){
    this.root.find('#url').val('http://maps.google.com/?q='+encodeURI($('#direccion').val())+'&ll='+coords.lat()+','+coords.lng()+'&ie=UTF8&oe=UTF8&z=18');
}



回答2:


I just found out something cool that fixes the SetTimeout context in jQuery 1.4+.

You can use the jQuery.proxy to solve the context issue.

Here is my code:


    Application = function()
    {
        this.AMethod = function(){};

        setTimeout($.proxy(this.AMethod,this), 100);


    }

After the timeout, the Application.AMethod is executed and thus the "Application" context is maintained

LE: Alternativelly you can create your own proxy function very simply if you don't want your plugin limited only to jQuery 1.4+ :


    function proxy(func, context)
    {
        return function(){ return func.apply(context, arguments);}
    }



来源:https://stackoverflow.com/questions/4587561/jquery-plugin-context-and-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!