Javascript jQuery插件、上下文和setTimeout
我正在为jQuery编写一个插件,我脑子里乱七八糟地想着javascript中的上下文问题 这是我的插件的简化版本:Javascript jQuery插件、上下文和setTimeout,javascript,jquery,this,settimeout,Javascript,Jquery,This,Settimeout,我正在为jQuery编写一个插件,我脑子里乱七八糟地想着javascript中的上下文问题 这是我的插件的简化版本: (function($){ $.fn.myplugin = function(options){ return new MyPlugin(this, options); }; function MyPlugin(el, o ) { this.root = el; this.input_box = el.find('#the_input');
(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);
我已经读到setTimeout将上下文设置为全局对象,所以我做了闭包,以便能够将上下文传递给search\u address
函数。这允许我从geocode
函数中的回调调用select_address
,但此回调正在调用select_address
,并且在那里再次出现了不需要的上下文:self.root
我完全不知道如何处理上下文,我认为在初始化“对象”时使用var self=this
可以避免这些问题
我必须注意的是,可以直接调用
select\u address
。使用this
来引用当前上下文:
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');
}
我刚刚发现了一些很酷的东西,修复了jQuery1.4+中的SetTimeout上下文 您可以使用jQuery.proxy来解决上下文问题 这是我的密码: Application = function() { this.AMethod = function(){}; setTimeout($.proxy(this.AMethod,this), 100); } 应用程序=函数() { this.AMethod=函数(){}; setTimeout($.proxy(this.AMethod,this),100); } 超时后,将执行Application.AMethod,从而维护“Application”上下文 乐: 或者,如果您不希望插件仅限于jQuery 1.4+,您可以非常简单地创建自己的代理函数: function proxy(func, context) { return function(){ return func.apply(context, arguments);} } 函数代理(函数,上下文) { 返回函数(){return func.apply(上下文,参数);} }
为什么赛尔夫不在那里工作?请记住,select_地址可以直接调用。。。我想知道一个规则来处理这个问题,避免反复试验。
self
是一个变量,但它不在当前范围内。如果您需要的是当前上下文,您可以使用this
,当this
可能更改时,您只需使用引用持有者,如self
,就像在您不控制的回调中一样。因此,我应该在上下文可能更改的任何位置创建“self”var,并且不能依赖于在初始值设定项中创建的self。。。因此,将上下文传递给回调是一种很好的做法?@clinisbut-如果您不控制它们,是的,这是一个很好的解决方案,特别是在setTimeout()
之类的情况下,或者创建一个闭包来保留上下文。在您的情况下,不需要传入self
,您可以代替self.search\u地址(self)代码>doself.search\u address.call(self)
和此
将位于搜索地址
函数中的self
。.call()
的第一个参数是上下文:)