Reputation: 1701
How do I turn this javascript into coffeescript?
$(function() {
function AppViewModel() {
this.firstName = ko.observable();
}
ko.applyBindings(new AppViewModel());
});
I tried this but it breaks the knockoutjs bindings
jQuery ->
AppViewModel = ->
this.firstName = ko.observable("something")
ko.applyBindings(new AppViewModel())
Here's what coffeescript produces
(function() {
jQuery(function() {
var ViewModel;
ViewModel = function() {
return this.firstName = ko.observable();
};
return ko.applyBindings(new ViewModel());
});
}).call(this);
Upvotes: 0
Views: 557
Reputation: 1170
I spent ages on this. I changed my method from what is similar to the introduction example (And the original post) to the one above with "classes" and then back again. What is breaking is the returns produced by the coffeescript and there is a really simple solution:
$ ->
AppViewModel = ->
@firstname = ko.observable 'andrew'
@lastname = ko.observable 'plumdog'
@fullname = ko.computed =>
@firstname() + ' ' + @lastname()
@
By explicitly returning @ at the end, any returns are fixed. I included 2 more lines than the original question, please note the use of => for computed's as these need to be run in the context of the original function.
Upvotes: 1
Reputation: 1701
This did the trick. But I think the real solution is - don't use coffeescript when learning knockoutjs
jQuery ->
class AppViewModel
firstName : ko.observable()
ko.applyBindings(new AppViewModel)
Upvotes: 4
Reputation: 11
That's not quite how you do objects in CoffeeScript. You should probably be doing something like:
jQuery ->
AppViewModel =
firstName: ko.observable()
ko.applyBindings(new AppViewModel())
Checkout: http://arcturo.github.com/library/coffeescript/index.html for a good reference.
Upvotes: 1
Reputation: 26690
In the CoffeeScript version you making the ko.applyBindings() happen as part of the jQuery document ready (since it's indented as part of it) whereas in the original JavaScript the ko.applyBindings() happened outside of it.
Try moving the ko.applyBindings(new AppViewModel()) line all the way to the left.
You can see the effect of this by looking generated JavaScript in your original code and the new one.
Upvotes: 0