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.
The equivalent of your JavaScript would be this:
You have to add
@tohasResultsto make it into an instance variable reference and you need to indent@hasResults.subscribeanother 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: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 currentthis:The fat-arrow is the usual replacement for the
var self = this;JavaScript idiom.