我对Rails中的Coffee脚本没有什么大的麻烦,因此只要有了原理和理解,就可以单独使用我的脚本了。
我有这样的咖啡脚本:
->
$('form').on 'click', '.add_fields', (event) ->
alert('my test message')
被编译为
(function() {
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
// You can use CoffeeScript in this file: http://coffeescript.org/
$(function() {
return $('form').on('click', '.add_fields', function(event) {
return alert('my test message');
});
});
}).call(this);
我遇到的问题是事件永远不会触发,当我手动将编译代码的这一部分放在控制台中时,事件就会触发,但是我无法获得最外部的功能。我是用错了吗,还是有人可以向我解释call(this)的工作原理,以便可以在咖啡脚本中放入适当的结构?
$(function() {
return $('form').on('click', '.add_fields', function(event) {
return alert('my test message');
});
});
谢谢。
答案 0 :(得分:0)
这是正在运行的最终咖啡脚本
$(document).on('turbolinks:load', ->
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('fields').replace(regexp, time))
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault())