How do you limit CoffeeScript (or JavaScript) execution to a particular controller and action in Rails 3.1?

前端 未结 5 609
攒了一身酷
攒了一身酷 2021-01-02 09:50

The new Rails 3.1 asset pipeline is really nice, but since all CoffeeScript (or JavaScript) files get melded down into a single file that is included in every page, it raise

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-02 10:21

    If you are using the gon gem for your vars in coffee script you can use this pattern:

    Put a flag for every action in the controller:

      def index
        @gps_coords = GpsCoord.all
    
        # Flag for the CoffeeScript to decide which part to run
        gon.index = true;
      end
    
      def show
        @gps_coord = GpsCoord.find(params[:id])
    
        gon.lat = @gps_coord.latitude
        gon.lon = @gps_coord.longitude
    
        gon.show = true;
      end
    

    In the correlating coffee script use those flags to distiguish between the both actions:

      # index action?
      if gon.index? 
        first_coord = gon.gps_coords[0]
        map.setView([first_coord.latitude, first_coord.longitude], 15);
    
      # show action?
      if gon.show?
        map.setView([gon.lat, gon.lon], 15);
    

提交回复
热议问题