1

我有一个 CoffeeScript 对象,它在触发操作后给我一个奇怪的错误。

对象加载时不会发生意外,尽管一旦完成触发回调的操作,我就会收到错误消息:

this.update 不是函数 return this.update(value);

有谁知道为什么会发生此错误?我最好的猜测是jQuery.rating 调用中的this对象实际上是指一个 jQuery 对象,而不是 rating 对象?

我的 CoffeeScript 代码是:

jQuery ->
    new Rating()

class Rating
    constructor: ->
        $('.auto-submit-star').rating
            callback: 
                (value, link) -> @update value

    update: (value) =>
        $.ajax
            type: 'post'
            url: $('#new_rating').attr('action')
            data: 'rating': value
        .done ( msg ) -> 
            alert( msg )

代码编译为:

var Rating,
  __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

Rating = (function() {

  function Rating() {
    this.update = __bind(this.update, this);
    $('.auto-submit-star').rating({
      callback: function(value, link) {
        return this.update(value);
      }
    });
  }

  Rating.prototype.update = function(value) {
    return $.ajax({
      type: 'post',
      url: $('#new_rating').attr('action'),
      data: {
        'rating': value
      }
    }).done(function(msg) {
      return alert(msg);
    });
  };

  return Rating;

})();
4

2 回答 2

4

您的rating插件可能将 .callback作为一个简单的函数或在 DOM 元素的上下文中调用,因此@(AKA this)可能是window您的.auto-submit-star元素。无论如何,@不​​是您的Rating对象并且没有update方法,因此您会收到错误消息。

标准方法是通过粗箭头 ( =>)使用绑定函数:

$('.auto-submit-star').rating
    callback: 
        (value, link) => @update value
于 2013-02-19T07:05:57.510 回答
0

我遇到了一个类似的错误:'fn.apply is not a function' 结果是我有一个与方法同名的构造函数参数。

do->
  angular.module 'myservices'
  .service 'averyspecialservice', ['$log', '$rootScope'
    class AVerySpecialService
      constructor: (@log, @rootScope)->

      log: (message)=>
        //do some magic here
        return
  ]
  return

因此,'log' 被定义为一种方法和注入值,并且用如此模糊的错误消息找到错误的原因被证明很有趣...... JavaScript 不是很棒吗?

于 2015-05-31T16:16:53.443 回答