咖啡脚本中的回调

时间:2015-02-09 17:26:14

标签: javascript callback coffeescript

我在coffeescript中有以下功能:

@get_person = (person_id) ->
  $.ajax '/people/'+person_id,
    type: 'GET'
    dataType: 'text'
    error: (jqXHR, textStatus, errorThrown) ->
        $('body').append "AJAX Error: #{textStatus}"
    success: (data, textStatus, jqXHR) ->
        $('.right-bar').html(data)  ->
            alert 1
            $('#interaction_filter').chosen()

的一部分
$('.right-bar').html(data)  ->

完美无缺,但下面的回调不会执行。我究竟做错了什么?控制台中没有显示任何内容。

3 个答案:

答案 0 :(得分:1)

你不能这么做:

$('.right-bar').html(data) ->

语法不允许,你可以确定这个

$('.right-bar').html (data) ->

如下所示:http://api.jquery.com/html/

请考虑在html和(数据)之间添加空格 - >

答案 1 :(得分:0)

通过CoffeeScript编译器运行后,我得到以下输出:

this.get_person = function(person_id) {};

$.ajax('/people/' + person_id, {
  type: 'GET',
  dataType: 'text',
  error: function(jqXHR, textStatus, errorThrown) {
    return $('body').append("AJAX Error: " + textStatus);
  },
  success: function(data, textStatus, jqXHR) {
    return $('.right-bar').html(data)(function() {
      alert(1);
      return $('#interaction_filter').chosen();
    });
  }
});

我相信你想要做的是将调用链接到html()。如果是这样,它将如下所示:

@get_person = (person_id) ->
    $.ajax '/people/'+person_id,
        type: 'GET'
        dataType: 'text'
        error: (jqXHR, textStatus, errorThrown) ->
            $('body').append "AJAX Error: #{textStatus}"
        success: (data, textStatus, jqXHR) ->
            $('.right-bar').html(data).html ->
                alert 1
                $('#interaction_filter').chosen()

答案 2 :(得分:-1)

Coffeescript是空格敏感的,所以你需要缩进你的回调体,使其成为该函数的一部分。

正如安东尼所指出的,原始代码的前几行编译为

this.get_person = function(person_id) {};

$.ajax('/people/' + person_id, {
....

换句话说,分配一个对this.get_person无效的函数,然后进行ajax调用。

假设您希望在函数内发生ajax调用,请尝试:

@get_person = (person_id) ->
    $.ajax '/people/'+person_id,
        type: 'GET'
        dataType: 'text'
        error: (jqXHR, textStatus, errorThrown) ->
            $('body').append "AJAX Error: #{textStatus}"
        success: (data, textStatus, jqXHR) ->
            $('.right-bar').html(data)  ->
                alert 1
                $('#interaction_filter').chosen()

缩进$.ajax行使其成为回调函数的一部分。

如果您想在Try Coffeescript

上尝试更多解决方案
相关问题