在Rails应用程序中设置Javascript轮询

时间:2014-10-01 16:42:36

标签: javascript jquery ruby-on-rails coffeescript polling

我对javascript非常陌生,我试图在rails应用中设置轮询,以便从活动模型中提供简化的活动源。我在这里密切关注民意调查Railscast:http://railscasts.com/episodes/229-polling-for-changes-revised?view=asciicast

我已经设置了一个非常简单的测试警报,可以在页面加载时触发,但是当我加载页面时警报不会出现。我希望有人可以澄清为什么它不会出现。

以下是观点:

<h4>Activities</h4>

<div class="well col-sm-5 activity_monitor" data-url="<%=activities_path%>">
<% @activities.each do |activity| %>
Student <%= activity.trackable_id %> began a tutoring session at <%=activity.created_at %>
<br>
<% end %>
</div>

这是我的简单咖啡:

ActivityPoller =
  poll: ->
    setTimeout @request, 5000

  request: ->
    $.get($('.activity_monitor').data('url'))

jQuery ->
  if $('.activity_monitor').length > 0 
    ActivityPoller.poll()

这是控制器:

class ActivitiesController < ApplicationController
  def index
    @activities=Activity.all
  end 
end

这是index.js.erb文件:

alert("This is a test alert");

当我加载页面时,这是我在控制台中看到的输出:

Consider using 'dppx' units, as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi) activities:1
Uncaught ReferenceError: define is not defined wizard.js?body=1:10(anonymous function) wizard.js?body=1:10
GET http://localhost:8080/assets/jquery.nanoscroller.min.js.map 404 (Not Found) activities:102
'Range.detach' is now a no-op, as per DOM (http://dom.spec.whatwg.org/#dom-range-detach). bootstrap3-wysihtml5.min.js?body=1:56
The "fb-root" div has not been created, auto-creating sdk.js:56

1 个答案:

答案 0 :(得分:0)

我发现未调用javascript警报,因为控制器操作没有明确的respond_to javascript块。令人困惑的是Railscast在源代码中没有这个respond_to块。它适用于那种情况,因为没有index.html.erb文件。在我的例子中,我有一个index.html.erb文件,因此有必要指定各种respond_to选项,以便Rails知道要渲染的内容。