简体   繁体   English

重构Rails Controller /视图以调用Javascript / jQuery

[英]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: 然后在views/controller_name/_stage_two.js.erb有:

$('.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. 因此,基本上,控制器动作本质上是呈现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? 那个特定的javascript只是从页面上删除一个元素,更改内容,然后将其淡入。是否有更好的方法呢? I know typically javascript lies in the app/assets/javascripts . 我知道通常javascript位于app/assets/javascripts

Your current implementation is quite DRY already and standard way. 您当前的实现已相当DRY和标准方式。

The html request should also render the same partial but with layout. html请求还应该呈现相同的局部但具有布局。

The js request should render js response(rendering partial) and update the portion of page. js请求应呈现js响应(局部渲染)并更新页面的一部分。

I know typically javascript lies in the app/assets/javascripts. 我知道通常javascript位于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. 这些就是您的资产,这个stage_two.js.erb并不是您的资产文件的本质,而是您对js响应的操作处理。

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请求并接收json响应以更新视图,但是对于很多情况(尤其是处理大数据时)失败的情况,当前的实现就可以了……

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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