I’m trying to implement knockout.js in Rails 3.2.6. I’m using the Gem https://github.com/jswanner/knockoutjs-rails.
I’m having trouble loading the ViewModel.
Here’s my HTML for debugging
<div data-bind="text: ko.toJSON(users)"></div>
Here’s the JavaScript compiled from CoffeeScript. The file is users.js.coffee and is included in the asset pipeline via //= require_tree . in application.js
(function() {
jQuery(function() {
var User, UserViewModel;
User = function(id, name) {
var self;
self = this;
self.id = ko.observable(id);
self.name = ko.observable(name);
return self.followers_count_message = ko.computed(function() {});
};
UserViewModel = function() {
var self;
self = this;
self.users = ko.observableArray([new User('1111', 'test name'), new User('1112', 'test name2')]);
self.addUsers = function() {
return self.users.push(new User('1113', 'test name'));
};
return self.addUsers();
};
ko.applyBindings(new UserViewModel());
return alert('done');
});
}).call(this);
Upon loading, the div displays this: [null,null,null]
The odd thing is if I implement this in jsFiddle, it seems to work. See this: http://jsfiddle.net/netwire88/HXYHU/2/
Thoughts, ideas?
UPDATE: 7/31/2012
I was able to fix this by changing the functions to remove the return. However, I would like to move it to another CoffeeScript file.
I tried this in users.js.coffee, however, I’m getting error Uncaught TypeError: Cannot read property 'nodeType' of null
User = (id, name) ->
self = undefined
self = this
self.id = ko.observable(id)
self.name = ko.observable(name)
@
UserViewModel = ->
self = this
self.users = ko.observableArray([new User("1111", "test name"), new User("1112", "test name2")])
self.addUsers = ->
self.users.push new User("1113", "test name")
self.addUsers()
@
ko.applyBindings new UserViewModel()
You should notice a very, very important difference between the code you posted, and the code in the fiddle: your viewmodels return single properties, the fiddle’s viewmodels have no return.
Your code is creating invalid viewmodels. If you uncomment those returns in your fiddle, it breaks in exactly the same way. You didn’t post the coffeescript for us to look at, but this is definitely the issue.
Bad Viewmodel:
Good Viewmodel
Same goes for the
UserViewModel.