2012-12-16 35 views
0

我想从ajax调用的成功节点调用一个窗口小部件函数,但是,我没有成功。如何从ajax成功调用JQuery小部件函数?

我的应用程序允许用户在googlemaps上添加一些标记并附上一些说明。它使用JQuery-addresspicker部件和Rails。我添加了一个负责添加标记的函数,它显示一个带有描述textarea的表单和一个提交信息的按钮。所以,在用户提交后,应用程序会调用Ajax函数来存储用户的数据,如果成功,我想调用另一个小部件函数,例如关闭InfoWindow。

问题是,我不知道如何从成功的Ajax节点调用另一个小部件函数。

JQuery-addresspicker.js 
. 
. 
. 

_addFormListener: function(map, marker) { 
    var form = $(".add-form").clone().show(); 
    var infoWindowContent = form[0]; 
    var infoWindow = new google.maps.InfoWindow({ 
     content: infoWindowContent 
    }); 

    google.maps.event.addListener(marker, "click", function() { 
     infoWindow.open(map, this); 
    }); 

    form.submit(function (event){ 
     event.preventDefault(); 

     var description = $("textarea[name=description]", this).val(); 
     var latitude = marker.getPosition().lat(); 
     var longitude = marker.getPosition().lng(); 

     var data = { 
     description : description, 
     latitude  : latitude, 
     longitude  : longitude 
     }; 

     $.ajax({ 
     type : "POST", 
     url : "/places", 
     data: {place: data}, 
     beforeSend: function(x) { 
      x.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')) 
     }, 
     success: function(x) { 
      this._closeFormFields(); // Not working! 
     } 
     }); 
    }); 
}, 

_cleanFormFields: function() { 
    console.log("testing"); 
} 
. 
. 

PlacesController 
def create 
@place = Place.new(params[:place]) 

if @place.save 
    redirect_to places_path 
else 
    render :status => 422 
end 

浏览器的控制台提出了“遗漏的类型错误:对象[对象]窗口有没有方法 '_cleanFormFields'

任何想法感谢

+0

在_closeFormFields面前摆脱“本”。 – RadBrad

+0

感谢您的回复,RadBrab。我试过了,但现在的异常是这样的:“未捕获的ReferenceError:_cleanFormField未定义” – hugalves

+0

如果在_addFormListener方法之前定义了_cleanFormFields,该怎么办? –

回答

0

这里的问题是范围?! 这个 - ajax调用覆盖这个来引用ajax调用对象,并且你松开了widget的引用。

为了解决这个问题,只需添加一个变量来存储参考部件像

form.submit(function (event){ 
    event.preventDefault(); 

    var description = $("textarea[name=description]", this).val(); 
    var latitude = marker.getPosition().lat(); 
    var longitude = marker.getPosition().lng(); 

    var data = { 
    description : description, 
    latitude  : latitude, 
    longitude  : longitude 
    }; 

    //new widget reference var (this here still refers to the widget) 
    var widget = this; 

    $.ajax({ 
    type : "POST", 
    url : "/places", 
    data: {place: data}, 
    beforeSend: function(x) { 
     x.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')) 
    }, 
    success: function(x) { 
     //now use the var widget here 
     widget._closeFormFields(); // Works! 
    } 
    }); 
});