JSFiddle - React, Tailwind, and code Playground
by ingro
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<script src="https://raw.github.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.js"></script>
Original Array
<div class="container" data-bind="sortable: {data: posts, afterMove: changeTime, beforeMove: checkSort} ">
<div class="item">
<span data-bind="text: time"></span>
-
<span data-bind="text: title"></span>
</div>
</div>
<hr/>
Filtered
<div class="container" data-bind="sortable: {data: filter, afterMove: changeTime, beforeMove: checkSort} ">
<div class="item">
<span data-bind="text: time"></span>
-
<span data-bind="text: title"></span>
</div>
</div>
<hr/>
<button id="save" data-bind="click: $root.save" class="btn btn-success">Save</button>
<button id="filter" data-bind="click: $root.apply_filter" class="btn btn-success">Filter</button>
<div id="result"></div>
CSS
.item{
display: block;
background: #C0C0C0;
margin-bottom: 5px;
width: 200px;
}
.container {
margin: 20px;
padding: 5px;
border: 1px solid black;
width: 200px;
}
JavaScript
function GridModel() {
var self = this,
posts = [
{
time: "07:00",
title: "test#1",
type: "odd"},
{
time: "08:00",
title: "work#2",
type: "even"},
{
time: "09:00",
title: "task#3",
type: "odd"},
{
time: "10:00",
title: "sleep#4",
type: "even" },
{
time: "11:00",
title: "wake#5",
type: "odd" }
],
postmapping = {
key: function(item) { return ko.utils.unwrapObservable(item.time); }
};
self.posts = ko.mapping.fromJS(posts, postmapping);
self.times = ko.observableArray(["07:00", "08:00", "09:00", "10:00", "11:00"]);
self.filter_set = ko.observable("odd");
self.allowDrop = ko.observable("false");
self.filter = ko.computed(function(){
var tof = self.filter_set ();
if(tof == "all"){
return self.posts();
}
return ko.utils.arrayFilter(self.posts(),function(post){
return post.type() === tof;
});
});
self.apply_filter = function(){
self.filter_set("odd");
self.allowDrop("false");
}
self.changeTime = function(arg) {
var count = 0;
ko.utils.arrayForEach(self.posts(), function(post) {
post.time(self.times()[count]);
count++;
});
};
self.checkSort = function(arg) {
if(self.allowDrop() == "false"){
arg.cancelDrop = true;
}
};
self.save = function(){
$("#result").html(ko.toJSON(self.posts));
}
}
ko.bindingHandlers.visibleAndSelect = {
update: function(element, valueAccessor) {
ko.bindingHandlers.visible.update(element, valueAccessor);
if (valueAccessor()) {
setTimeout(function() {
...