I am trying to write a somewhat simple todo application using knockout.js and jquery mobile. The code works very well when I am just using knockout (replacing text in the main page on the fly as I add items). However, jquery mobile won’t render properly after adding items to a ko.observableArray.
I can see the code render properly for a split second, then the page refreshes and it is not showing ANY of the list items anymore.
The HTML:
<div data-role="page">
<div data-role="header">
<h1>Lists</h1>
</div>
<div data-role="content">
<ul data-bind="foreach: lists" data-role="listview" data-inset="true">
<li data-bind="text: name"></li>
</ul>
<form data-bind="submit: addList">
<input data-bind="value: newListName" placeholder="new list name" />
<button type="submit">Add New List</button>
</form>
</div>
<div data-role="footer" data-position="fixed">
<h1>Footer</h1>
</div>
</div>
The Javascript:
function List(data) {
var self = this;
self.name = ko.observable(data.name);
self.tasks = ko.observableArray([]);
}
function TaskListViewModel() {
var self = this;
self.currentList = ko.observable(new List({ name: "Inbox" }));
self.newListName = ko.observable('');
self.lists = ko.observableArray([self.currentList()]);
self.addList = function() {
self.currentList(new List({ name: this.newListName() }));
self.lists.push(self.currentList());
self.newListName('');
};
}
More specifically, I can see a list item with “Inbox”, with a text field below and then a button below that. When I type in another list item into the field and click “Add”, I can momentarily see everything correctly rendered. Then it refreshes and I see no list items.
Any help appreciated.
It sounds like the form is being submitted and the page reloaded. Try the workaround here: jquery mobile and knockout form submit binding