thrice801
thrice801

Reputation: 1671

knockout model to coffeescript class syntax conversion

So I'm trying to convert a knockout model into a coffeescript class, haven't used coffee until now, having trouble with a syntax in how to call the property.subscribe knockout function, via coffeescript (and in my class). Presently the code looks like (severely dumbed down to get point across)

var Autocomplete = function(){
  var self = this;
  self.displayResults = ko.observable(false);
  self.results = ko.observableArray([]);
  self.hasResults = ko.observable(false);

    self.hasResults.subscribe(function(newValue){
        if(newValue == true) {
            self.displayResults(true);
        } else {
            self.displayResults(false);
        }
    });

}

But basically what Im trying to do is:

class ClientAutoComplete
  constructor: ->
    @hasResults = ko.observable(false)  
    @results = ko.observableArray([])  
    @displayResults = ko.observable(false)

  hasResults.subscribe: (newValue) ->
    @displayResults(newValue)

What I cant figure out is how to call the property.subscribe method correctly, ive tried a couple different syntaxes but to no avail. Can anyone shed any light on this? Much appreciated in advance.

Upvotes: 1

Views: 631

Answers (1)

mu is too short
mu is too short

Reputation: 434606

The equivalent of your JavaScript would be this:

class ClientAutoComplete
  constructor: ->
    @displayResults = ko.observable(false)
    @results = ko.observableArray([])  
    @hasResults = ko.observable(false)  

    @hasResults.subscribe (newValue) =>
      @displayResults(newValue)

You have to add @ to hasResults to make it into an instance variable reference and you need to indent @hasResults.subscribe another level to get it into the constructor. You also don't want a colon on @hasResults.subscribe, that's a function call, not a property definition; you could also write it like this:

@hasResults.subscribe( (newValue) =>
  @displayResults(newValue)
)

if you need to be reminded that it is a function call. I tend to include the parentheses if the anonymous function is bigger than a one-liner.

The fat-arrow (=>) binds the anonymous function to the current this:

The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to each, or event-handler functions to use with bind. Functions created with the fat arrow are able to access properties of the this where they're defined.

The fat-arrow is the usual replacement for the var self = this; JavaScript idiom.

Upvotes: 2

Related Questions