[英]Rails - can I call a controller method from my ActionCable coffeescript?
I'm building a quiz app that leads all participants synchroneously through multiple stages: 我正在构建一个测验应用程序,该应用程序可以在多个阶段同步引导所有参与者:
If a participant loses his connection and reconnects, I want them to be able to immediately pick up where they left off. 如果参与者失去了连接并重新连接,我希望他们能够立即从中断的地方接听。
I always save the current phase to the db. 我总是将当前阶段保存到数据库。 So I'm thinking of calling a method show_current_phase(curent_user)
in the connected
method of my ActionCable channel. 因此,我正在考虑在我的ActionCable通道的connected
方法中调用方法show_current_phase(curent_user)
。 Since I feel like it would make sense to place this method in the corresponding controller for my custom QuizSession model, I'd like to know: 由于我觉得将这种方法放置在自定义QuizSession模型的相应控制器中很有意义,因此我想知道:
Is it possible to call a controller method in my coffeescript (frontend) and have it return an object? 是否可以在我的coffeescript(前端)中调用控制器方法并使它返回一个对象?
Or how do I update the DOM tree of only the user who reconnected without broadcasting to all the other participants? 或者,如何仅更新没有重新广播给所有其他参与者的用户的DOM树?
You can just turning your .coffee
file into an .haml
or .erb
template. 您可以将.coffee
文件转换为.haml
或.erb
模板。
# myscript.js
var myPath = '/some_path';
Will become 会变成
# myscript.js.erb
var myPath = <%= some_controller_path %> ;
In case you are using haml , the process is not really different. 如果您使用haml ,则过程实际上没有什么不同。
# myscript.coffee
myPath = '/some_path'
Will become 会变成
# myscript.coffee.haml
myPath = '#{ some_controller_path }'
Obviously, you can create .js.haml
and .coffee.erb
files as well. 显然,您也可以创建.js.haml
和.coffee.erb
文件。
In your case, you could have something like this in your .coffee.haml
: 就您而言,您的.coffee.haml
可能包含以下.coffee.haml
:
myFunction = ->
res = $.ajax(
url: '#{method_controller_path}'
method: 'GET'
data:
variableParam: '#{@my_controller_var}'
anotherParam: 'anotherParam'
dataType: 'json'
success: (res) ->
res
)
doSomething res
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.