Knockoutjs.com - Contacts Editor
http://stackoverflow.com/questions/11812925/inserting-values-into-knockout-viewmodel
HTML
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<div class="liveExample">
<div>
<input type="text" placeholder="question" data-bind="value:inputQ.question">
<input type="text" placeholder="type" data-bind="value:inputQ.qtype">
<button data-bind="click: addQuestion">Add a question</button>
</div>
<div id="questionList">
<ul data-bind="foreach: questions" id="sortable" class="ui-sortable">
<li>
<label data-bind="text: question">Question 1</label></li>
</ul>
</div>
<p>
<button data-bind="click: save, enable: questions().length > 0">Save to JSON</button>
</p>
<textarea data-bind="value: lastSavedJson" rows="5" cols="60" disabled="disabled"> </textarea>
</div>
CSS
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }
.liveExample TR { vertical-align: top; }
.liveExample TABLE, .liveExample TD, .liveExample TH { padding: 0.2em; border-width: 0; margin: 0; }
.liveExample TD A { font-size: 0.8em; text-decoration: none; }
.liveExample table.contactsEditor > tbody > TR { border-bottom: 1px solid silver; }
.liveExample td input { width: 8em; }
li { list-style-type: disc; margin-left: 20px;font-size:1.2em }
JavaScript
var initialData = [
{
question: "Question 1",
qtype: "Feedback"},
{
question: "Question 2",
qtype: "Rating"}
];
var Question = function(q, t) {
var self = this;
self.question = ko.observable(q);
self.qtype = ko.observable(t);
return self;
};
var ViewModel = function(questions) {
var self = this;
self.questions = ko.observableArray(ko.utils.arrayMap(questions, function(question) {
return new Question(question.question, question.qtype);
}));
self.inputQ = new Question();
self.addQuestion = function() {
self.questions.push(new Question(self.inputQ.question(), self.inputQ.qtype()));
};
self.removeQuestion = function(question) {
self.questions.remove(question);
};
self.save = function() {
self.lastSavedJson(JSON.stringify(ko.toJS(self.questions), null, 2));
};
self.lastSavedJson = ko.observable("");
};
var view_model = new ViewModel(initialData);
ko.applyBindings(view_model);
$(function() {
$( "#sortable" ).sortable({
revert: true,
stop: function(event, ui) { console.log("stop event")},
start : function ( event, ui ) {
ui.item.data( 'previous_index', ui.item.index() );
},
// start
update : function ( event, ui ) {
var question = view_model.questions.splice(
ui.item.data( 'previous_index' ), 1
)[0];
view_model.questions.splice( ui.item.index(), 0, question );
ui.item.removeData( 'previous_index' );
}
// update
});
});