简体   繁体   中英

Refactoring Rails Controller / Views to call Javascript / jQuery

I'm trying to refactor some legacy code at the moment. It currently goes something like this:

Controller

def create
  # do stuff

  respond_to do |format|
    format.html { do stuff }
    format.js { render partial: 'stage_two', locals: { some instance variables } }
  end
end

Then in the views/controller_name/_stage_two.js.erb there is:

$('.some_element').children().fadeOut( function() {
  $('.some_element').children().remove();
  $('.some_element').html("<%=j render partial: 'form', locals: { stuff } %>");
  $('.some_element .stage_two').fadeIn();
});

So basically the controller action is essentially rendering javascript. And that particular javascript is just removing an element from the page, changing the contents, then fading it back in. Is there a better way to do this? I know typically javascript lies in the app/assets/javascripts .

Your current implementation is quite DRY already and standard way.

The html request should also render the same partial but with layout.

The js request should render js response(rendering partial) and update the portion of page.

I know typically javascript lies in the app/assets/javascripts.

Those are your assets, this stage_two.js.erb is not essentialy your assets file, this is instead your action handling for the js response.

Definitely for smaller update actions you can use json request and receive json response to update view, but for many of the cases(esp. when dealing with large data) that fails, and your current implementation is fine in that...

通常,执行此操作的通常方法是让控制器返回JSON(我希望它呈现变量的格式化版本),然后让JS进行常规的AJAX调用并使用JSON数据更新元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM