Using Coffeescript classes with ko.computed

465 views
Skip to first unread message

Brian Vallelunga

unread,
May 30, 2012, 4:10:23 PM5/30/12
to knock...@googlegroups.com
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());

rpn

unread,
May 31, 2012, 12:31:55 AM5/31/12
to knock...@googlegroups.com
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

Thibaut Barrère

unread,
May 31, 2012, 3:46:34 AM5/31/12
to knock...@googlegroups.com
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
--

Brian Vallelunga

unread,
May 31, 2012, 9:04:11 AM5/31/12
to knock...@googlegroups.com
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.

Brian Vallelunga

unread,
May 31, 2012, 9:36:06 AM5/31/12
to knock...@googlegroups.com
Yes, thanks. This does work. I wasn't defining it in the constructor, which seems to have been my mistake.
Reply all
Reply to author
Forward
0 new messages