Created
March 13, 2014 02:39
-
-
Save akras14/9521003 to your computer and use it in GitHub Desktop.
Basic Knockout Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<h3>Demo Table</h3> | |
<table border="1px"> | |
<thead> | |
<tr> | |
<th>Task Name</th> | |
</tr> | |
</thead> | |
<tbody data-bind="foreach: tasks"> | |
<tr> | |
<td data-bind="text: name()"></td> | |
</tr> | |
</tbody> | |
</table> | |
<h3>Demo Task List</h3> | |
<ul data-bind="foreach: tasks"> | |
<li data-bind="text: name()"></li> | |
</ul> | |
<b>Change Me</b> | |
<select data-bind="options: tasks, optionsText: 'name', value: selectedTask, optionsCaption: 'Choose Task to Edit'"></select> <br /> | |
<b>Edit Me</b> | |
<input type="text" data-bind="value: newTaskName, valueUpdate: 'afterkeydown'"/> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function () { | |
function Task(taskName){ | |
this.name = ko.observable(taskName); | |
} | |
function AppViewModel() { | |
var self = this; | |
//List of all tasks | |
self.tasks = ko.observableArray([ | |
new Task("Call Work"), | |
new Task("Buy Milk"), | |
new Task("Go Home") | |
]); | |
self.selectedTask = ko.observable(); | |
//When new task is selected | |
self.selectedTask.subscribe(function(){ | |
if(self.selectedTask()){ | |
self.newTaskName(self.selectedTask().name()); | |
} else { | |
self.newTaskName(''); | |
} | |
}); | |
self.newTaskName = ko.observable(); | |
//When name in input filed is changed | |
self.newTaskName.subscribe(function(){ | |
if(self.selectedTask()){ | |
self.selectedTask().name(self.newTaskName()); | |
} | |
}); | |
} | |
//Apply 2 way data binding | |
ko.applyBindings(new AppViewModel()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment