Javascript Rails Live:动态地将Result从方法发送到浏览器
我试图将模型状态的更改通知用户的浏览器。我正在尝试使用Rails的live模块来实现这一点。以下是我到目前为止得到的信息:Javascript Rails Live:动态地将Result从方法发送到浏览器,javascript,ruby-on-rails,ruby,event-handling,dom-events,Javascript,Ruby On Rails,Ruby,Event Handling,Dom Events,我试图将模型状态的更改通知用户的浏览器。我正在尝试使用Rails的live模块来实现这一点。以下是我到目前为止得到的信息: require 'json' class Admin::NotificationsController < ActionController::Base include ActionController::Live def index puts "sending message" videos = Video.all response
require 'json'
class Admin::NotificationsController < ActionController::Base
include ActionController::Live
def index
puts "sending message"
videos = Video.all
response.headers['Content-Type'] = 'text/event-stream'
begin
if(params[:id].present?)
response.stream.write(sse({id: params[:id]},{event: "video_encoded"}))
end
rescue IOError
ensure
response.stream.close
end
end
private
def sse(object, options = {})
(options.map{|k,v| "#{k}: #{v}" } << "data: #{JSON.dump object}").join("\n") + "\n\n"
end
end
不幸的是,即使我使用curl触发事件,浏览器中的以下事件侦听器也不会启动:
var source = new EventSource('/notifications');
source.addEventListener("video_encoded", function(event) {
console.log("message")
console.log(event)
});
这样做的目的是,如果有更改,我希望稍后向某个页面添加dom元素。也许有更好的方法,但Ruby Live似乎是一个合适的解决方案。欢迎提供任何不同方法的提示或建议。您的用例似乎不是ActionController::Live的有效用例。您没有向浏览器发送流式输出。您对ID执行一次性检查并发送JSON输出
使用常规控制器,通过AJAX而不是EventSource获取请求。您的用例似乎不是ActionController::Live的有效用例。您没有向浏览器发送流式输出。您对ID进行一次性检查并发送JSON输出。那么,有什么更好的方法来处理它呢?使用常规控制器,但我如何将更改通知用户的浏览器。我有一个被触发的方法,如果该方法被触发,我需要在用户的浏览器中更改某些内容,而无需重新加载页面。使用AJAX并在成功回调时更新DOM。
var source = new EventSource('/notifications');
source.addEventListener("video_encoded", function(event) {
console.log("message")
console.log(event)
});