2012-12-16 39 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! 
    } 
    }); 
});