How to get the id field and send to the view

旧街凉风 提交于 2019-12-11 07:56:10

问题


I'd like to know how can I get the ID field from my Model to pass in the JavaScript that I call when I click in a marker.

My model:

acts_as_gmappable :process_geocoding => false, :lat => "lat", :lng => "lon"

My controller

def index
    @locales_markers = Locale.all.to_gmaps4rails
    respond_to do |format|
      format.html  { render :layout => false }
    end
end

My View

<%= gmaps("markers" => { "data" => @locales_markers } %>

<% content_for :scripts do %>
    <script>
        Gmaps4Rails.callback = function() {
            for (var i = 0; i <  this.markers.length; ++i) {
                google.maps.event.addListener(Gmaps4Rails.markers[i].serviceObject, 'click', function(){
                    $('#info').load('/messages/' **<HERE I'D LIKE TO PASS THE ID>**);
                    $('#info').dialog("open");
                });

            }
        };
    </script>
<% end %>

Thanks, Luciano


回答1:


Every marker property is stored and can be retrieved.

In your example, simply do:

$('#info').load('/messages/' + Gmaps4Rails.markers[i].id );

EDIT:

You should create another js function:

custom_listener = function(the_id) {
  return function(){
        $('#info').load('/messages/' + the_id );
        $('#info').dialog("open");
  };
};

And call it this way:

Gmaps4Rails.callback = function() {
 for (var i = 0; i <  this.markers.length; ++i) {
     google.maps.event.addListener(Gmaps4Rails.markers[i].serviceObject, 'click', custom_listener(Gmaps4Rails.markers[i].id));
  }
};



回答2:


I changed my controller to:

  def index
    @locales_markers = Locale.all.to_gmaps4rails do |locale|
      "\"id\": \"#{locale.id}\""
    end
    respond_to do |format|
      format.html  { render :layout => false }
    end
  end

and work fine, but, I'm not able to get the id value in the view.

How to solve it?

Thanks, Luciano



来源:https://stackoverflow.com/questions/6741452/how-to-get-the-id-field-and-send-to-the-view

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