Skip to content

Instantly share code, notes, and snippets.

@dealproc
Created September 26, 2013 03:52
Show Gist options
  • Save dealproc/6709693 to your computer and use it in GitHub Desktop.
Save dealproc/6709693 to your computer and use it in GitHub Desktop.
/// <reference path="../../Scripts/jquery-2.0.3.intellisense.js" />
/// <reference path="../../Scripts/jquery-2.0.3.js" />
///
define(["jquery", "knockout"],
function ($, ko) {
return function () {
var get = function (params) {
var resource = this.resource;
var deferred = $.Deferred(function (def) {
if (!params) {
def.reject();
}
$.ajax({
url: "/api/" + resource, // may need to be "/api/" + resource "/" + params.Id
type: "GET",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: params
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var getAll = function (params, options) {
var resource = this.resource;
var deferred = $.Deferred(function (def) {
$.ajax({
url: "/api/" + resource,
type: "GET",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: params
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var create = function (item) {
var data = ko.toJSON(item);
var resource = this.resource;
var deferred = $.Deferred(function (def) {
$.ajax({
url: "/api/" + resource,
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: data
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var update = function (item) {
var data = ko.toJSON(item);
var resource = this.resource;
var deferred = $.Deferred(function (def) {
$.ajax({
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var save = function (item) {
var resource = this.resource;
var self = this;
var deferred;
var updated = false;
var unwrapped = ko.toJS(item);
if (unwrapped && unwrapped.id && unwrapped.id > 0) {
updated = true;
deferred = self.update(item);
} else {
deferred = self.create(item);
}
deferred.updated = function (callback) {
if (updated) {
deferred.then(callback);
}
return deferred;
};
deferred.created = function (callback) {
if (!updated) {
deferred.then(callback);
}
return deferred;
};
return deferred;
};
var defineRequests = function (resource) {
return {
resource: resource,
get: get,
getAll: getAll,
save: save
}
};
return {
define: defineRequests
};
}();
});
<div class="container-fluid">
<div class="row-fluid">
<div class="span12">
<table data-bind="css: settings.tableClass">
<thead>
<tr data-bind="foreach: settings.ColumnDefinitions">
<th data-bind="css: $data.colClass">
<a href="#" data-bind="click: function () { $parent.toggleSorting($data); }">
<span data-bind="text: $data.headerText"></span>
<span data-bind="css: $data.bSortIcon"></span>
</a>
</th>
</tr>
</thead>
<tbody data-bind="foreach: settings.Items">
<tr data-bind="foreach: $parent.settings.ColumnDefinitions">
<td data-bind="css: $data.colClass, html: $parents[1].getCellValue($parent, $data)"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row-fluid">
<div class="span6">
<div class="dataTables_info">
showing
<span data-bind="text: recordInfo.lowerBound"></span>
to
<span data-bind="text: recordInfo.upperBound"></span>
of <span data-bind="text: recordInfo.totalItems"></span>
Entries.
</div>
</div>
<div class="span6 pagination" data-bind="with: pagerInfo">
<ul class="pull-right">
<li data-bind="css: { disabled: isFirstPage }"><a href="#" data-bind=" click: toPrevPage, disable: isFirstPage">Prev</a></li>
<!-- ko foreach: pageNumbers -->
<li data-bind="css: { disabled: $data === $parent.currentPage }"><a href="#" data-bind="click: function () { $parent.toPage($data) }, text: $data, disable: $parent.currentPage === $data"></a></li>
<!-- /ko -->
<li data-bind="css: { disabled: isLastPage }"><a href="#" data-bind=" click: toNextPage, disable: isLastPage">Next</a></li>
</ul>
</div>
</div>
</div>
/// <reference path="../../../Scripts/jquery-2.0.3.js" />
define([
'durandal/composition',
'jquery',
"dataservices/provider",
"plugins/observable"], function (composition, $, provider, observable) {
var sortModes = ["", "asc", "desc"];
var ctor = function () { };
ctor.prototype.recordCounts = [10, 25, 50, 100];
ctor.prototype.recordCount = 10;
ctor.prototype.recordInfo = {
lowerBound: 0,
upperBound: 0,
totalItems: 0
};
ctor.prototype.pagerInfo = {
maxPages: 1,
maxPageLinks: 5,
currentPage: 0,
pageNumbers: [],
isFirstPage: undefined,
isLastPage: undefined,
toPage: undefined,
toFirstPage: undefined,
toPrevPage: undefined,
toNextPage: undefined,
toLastPage: undefined
};
ctor.prototype.settings = {};
ctor.prototype.dataProvider = undefined;
ctor.prototype.activate = function (settings) {
var _Self = this;
this.settings = $.extend(true, settings, {
ColumnDefinitions: [],
ODataResource: settings.ODataResource || "",
tableClass: settings.tableClass || "table",
recordCount: settings.recordCount || 10
} || {});
this.dataProvider = provider.define(this.settings.ODataResource);
this.settings.Items = [];
this.settings.ColumnDefinitions = $.map(this.settings.ColumnDefinitions, function (item, index) {
var col = $.extend(true, item, {
dataProperty: item.dataProperty !== undefined ? item.dataProperty : undefined,
headerText: item.headerText !== undefined ? ko.observable(item.headerText) : ko.observable(""),
colClass: item.colClass !== undefined ? ko.observable(item.colClass) : ko.observable("span1"),
bSort: (item.bSort !== undefined) ? ko.observable(item.bSort) : ko.observable(false),
bSortDir: item.bSortDir !== undefined ? ko.observable(item.bSortDir) : ko.observable(""),
bSortIcon: ko.observable("")
});
if (col.bSort()) {
col.bSortIcon("icon-sort");
}
observable(col, "bSortDir").subscribe(function (value) {
switch (value) {
case "":
col.bSortIcon("icon-sort");
break;
case "asc":
col.bSortIcon("icon-sort-up");
break;
case "desc":
col.bSortIcon("icon-sort-down");
break;
default:
col.bSortIcon("");
break;
};
});
return col;
});
observable.defineProperty(this.pagerInfo, "isFirstPage", function () {
return _Self.pagerInfo.currentPage === 1;
});
observable.defineProperty(this.pagerInfo, "isLastPage", function () {
return _Self.pagerInfo.currentPage === _Self.pagerInfo.maxPages;
});
observable(this.pagerInfo, "currentPage").subscribe(function (value) {
var startPage = _Self.pagerInfo.currentPage - Math.floor(_Self.pagerInfo.maxPageLinks / 2);
if (startPage < 1) {
startPage = 1;
}
console.log("Start Page: " + startPage.toString());
var stopPage = startPage + _Self.pagerInfo.maxPageLinks - 1;
if (stopPage > _Self.pagerInfo.maxPages) {
stopPage = _Self.pagerInfo.maxPages;
}
if (((_Self.pagerInfo.maxPages - _Self.pagerInfo.maxPageLinks) <= startPage) && ((_Self.pagerInfo.maxPages - _Self.pagerInfo.maxPageLinks) > 0)) {
startPage = _Self.pagerInfo.maxPages - _Self.pagerInfo.maxPageLinks;
}
_Self.pagerInfo.pageNumbers = [];
for (var i = startPage; i <= stopPage; i++) {
_Self.pagerInfo.pageNumbers.push(i);
}
});
this.pagerInfo.toPage = function (pageNo) {
if (pageNo <= this.maxPages) {
_Self.loadData(pageNo);
}
};
this.pagerInfo.toFirstPage = function () {
_Self.pagerInfo.toPage(1);
};
this.pagerInfo.toPrevPage = function () {
if (this.currentPage - 1 >= 1) {
_Self.pagerInfo.toPage(this.currentPage - 1);
}
};
this.pagerInfo.toNextPage = function () {
if (this.currentPage + 1 <= this.maxPages) {
_Self.pagerInfo.toPage(this.currentPage + 1);
}
};
this.pagerInfo.toLastPage = function () {
_Self.pagerInfo.toPage(this.maxPages);
};
this.loadData(1);
};
ctor.prototype.loadData = function (pageNo) {
var _Self = this;
var pageIndex = pageNo - 1;
if (pageIndex < 0) {
pageIndex = 0;
};
var params = {
$inlinecount: "allpages",
$skip: pageIndex * this.recordCount,
$top: this.recordCount
};
var colSorting = $.grep(_Self.settings.ColumnDefinitions, function (colDef, colDefIdx) {
return colDef.bSort && colDef.bSortDir() !== "";
});
if (colSorting.length) {
var orderby = $.map(colSorting, function (col, idx) {
return col.dataProperty + " " + col.bSortDir();
}).join(",");
$.extend(true, params, {
$orderby: orderby
} || {});
}
_Self.dataProvider.getAll(params)
.then(function (data) {
_Self.settings.Items.removeAll();
for (var i = 0; i < data.Items.length; i++) {
_Self.settings.Items.push(data.Items[i]);
}
_Self.recordInfo.lowerBound = ((pageNo - 1) * _Self.recordCount) + 1;
_Self.recordInfo.upperBound = data.Items.length + (_Self.recordInfo.lowerBound - 1);
_Self.recordInfo.totalItems = data.Count;
_Self.pagerInfo.maxPages = Math.ceil(_Self.recordInfo.totalItems / _Self.recordCount);
// set this last so that we can get the page #'s in the pager.
_Self.pagerInfo.currentPage = pageNo;
});
};
ctor.prototype.getCellValue = function ($data, columnDefinition) {
if (columnDefinition.dataProperty !== undefined && $data[columnDefinition.dataProperty] !== undefined) {
return $data[columnDefinition.dataProperty];
}
return "";
};
ctor.prototype.toggleSorting = function (columnDefinition) {
if (columnDefinition.bSort) {
var modeIdx = sortModes.indexOf(columnDefinition.bSortDir()) + 1;
if (modeIdx > sortModes.length) {
modeIdx = 0;
}
columnDefinition.bSortDir(sortModes[modeIdx] || "");
this.pagerInfo.toFirstPage();
}
}
return ctor;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment