【问题标题】:Coffeescript Object method is not a functionCoffeescript 对象方法不是函数
【发布时间】:2015-06-01 00:16:53
【问题描述】:

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

虽然触发回调的操作完成后,我收到错误消息:

this.update 不是函数 返回 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;

})();

【问题讨论】:

    标签: jquery ruby-on-rails coffeescript


    【解决方案1】:

    您的rating 插件可能将callback 作为一个简单函数或在DOM 元素的上下文中调用,因此@(又名this)可能是window 或您的.auto-submit-star 元素。在任何情况下,@ 都不是您的 Rating 对象,并且没有 update 方法,因此您会遇到错误。

    标准方法是通过fat-arrow (=>) 使用绑定函数:

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

    【讨论】:

    • 感谢您的信息,您是正确的,胖箭头解决了问题。欣赏信息。
    【解决方案2】:

    我遇到了类似的错误:使用“fn.apply 不是函数”,结果是我有一个与方法同名的构造函数参数。

    do->
      angular.module 'myservices'
      .service 'averyspecialservice', ['$log', '$rootScope'
        class AVerySpecialService
          constructor: (@log, @rootScope)->
    
          log: (message)=>
            //do some magic here
            return
      ]
      return

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

    【讨论】:

      猜你喜欢
      • 2014-09-12
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2016-10-10
      • 2013-03-02
      • 2015-04-11
      相关资源
      最近更新 更多