Using Coffeescript classes with ko.computed

Showing 1-5 of 5 messages
Using Coffeescript classes with ko.computed Brian Vallelunga 5/30/12 1:10 PM
I'm using Coffeescript's classes in my view models and am having issues creating ko.computed values. Specifically, the value of 'this' inside of the passed function is always set to Window, not the instance of my Coffeescript class. I've tried passing 'this' as the second parameter to the computed function, but it hasn't worked. Has anyone done this successfully?

Thanks for any help. Coffeescript has worked quite well thus far, with the exception of this one issue.

My CS class looks something like:

window.Section = class Section
    constructor: ->
        @options = ko.observableArray ['One', 'Two', 'Three']

    options: {}
    
    getComputed: ko.computed ->
        # I need access to the instance options here
        return @options


// My ViewModel, in JS

var viewModel = {
    sections: ko.observableArray()
}

viewModel.sections.push(new Section());
Re: Using Coffeescript classes with ko.computed rpn 5/30/12 9:31 PM
I am not a coffeescript user (currently), but could you define your Section like:

window.Section = class Section
    constructor: ->
        @options = ko.observableArray ['One', 'Two', 'Three']
        getComputed = ko.computed => 
            return @options
Re: Using Coffeescript classes with ko.computed Thibaut Barrère 5/31/12 12:46 AM
Hi Brian,

what Ryan did (using the fat arrow => instead of ->) works for me:

@formattedAmount = ko.computed(=> accounting.formatMoney(@amount()))

Sidenote (not a JS expert here, but!): it seems that you can define:

class @Section

instead of:

window.Section = class Section

hope this helps,

Thibaut
--
Re: Using Coffeescript classes with ko.computed Brian Vallelunga 5/31/12 6:04 AM
I've never seen the @ClassName syntax before, and can't find a reference to it on the CS site. That said, it works great. Thanks for the shortcut.
Re: Using Coffeescript classes with ko.computed Brian Vallelunga 5/31/12 6:36 AM
Yes, thanks. This does work. I wasn't defining it in the constructor, which seems to have been my mistake.