jQuery插件,上下文和setTimeout [英] jQuery plugin, context and setTimeout
问题描述
我正在为jQuery编写一个插件,但由于JavaScript的上下文问题,我一头雾水.
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);
我已经读过setTimeout将上下文设置为全局对象,所以我做了闭包以将上下文传递给search_address
函数.这使我可以从geocode
函数的回调中调用select_address
,但是此回调正在调用select_address
,因此上下文再次不受欢迎:找不到self.root
.
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.
我完全不知道如何处理上下文,尽管我在初始化对象"时使用var self=this
可以避免这些问题...
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...
我必须注意,select_address
可以直接调用...
I must note that select_address
can be called directly...
推荐答案
在那时使用this
来引用当前上下文:
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');
}
这篇关于jQuery插件,上下文和setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!