1

I have a CoffeeScript object which is giving me a strange error after an action is triggered.

The object loads without incident, although once the action is completed that triggers the callback I receive the error:

this.update is not a function return this.update(value);

Does anyone have an idea why this error has occurred? My best guess is the this object inside the jQuery.rating call is actually referring to a jQuery object, rather than the rating object?

My CoffeeScript code is:

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 )

The code compiles to:

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;

})();

2 Answers 2

4

Your rating plugin is probably calling the callback as a simple function or in the context of the DOM element so @ (AKA this) is probably window or your .auto-submit-star element. In any case, @ isn't your Rating object and doesn't have an update method so you're getting an error.

The standard approach is to use a bound function via the fat-arrow (=>):

$('.auto-submit-star').rating
    callback: 
        (value, link) => @update value
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info, you are correct the fat arrow resolved the issue. Appreciate the info.
0

I ran into a similar error : with 'fn.apply is not a function' and it turned out to be that I had a constructor parameter with the same name as a method.

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

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

So 'log' was defined as both a method and injected value and finding the cause of the error with such a vague error message proved fun... Isn't JavaScript wonderful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.