Skip to content

Instantly share code, notes, and snippets.

@RainerAtSpirit
Created July 29, 2012 13:20
Show Gist options
  • Save RainerAtSpirit/3198725 to your computer and use it in GitHub Desktop.
Save RainerAtSpirit/3198725 to your computer and use it in GitHub Desktop.
JayData + Knockout
define(['knockout', 'postbox', 'underscore'], function (ko, postbox) {
"use strict";
return function () {
var selectedList, allItems, take, takeValues, includeArray, orderBy, orderAsc, handleAfterRender, showTable,
chooseMap;
selectedList = ko.observable('No list selected').syncWith('selectedList');
allItems = ko.observableArray([]);
// defaults for OData requests
take = ko.observable(10);
takeValues = ko.observableArray([10, 20, 50]);
orderBy = ko.observable('Modified');
orderAsc = ko.observable(false);
includeArray = ko.observableArray(['CreatedBy', 'ModifiedBy']);
handleAfterRender = function (elements, data) {
$(elements).find('.prettyDate').prettyDate({ isUTC : true });
};
showTable = ko.computed(function () {
return selectedList() !== 'No list selected';
});
chooseMap = function (list) {
if (app.context[list].elementType.memberDefinitions.getMember('Title')) {
return function (item) {
return {
Id : item.Id,
Title : item.Title,
Modified : item.Modified,
Created : item.Created,
CreatedBy : item.CreatedBy.Name
};
};
}
else if (app.context[list].elementType.memberDefinitions.getMember('Name')) {
return function (item) {
return {
Id : item.Id,
Title : item.Name,
Modified : item.Modified,
Created : item.Created,
CreatedBy : item.CreatedBy.Name
};
};
}
else if (app.context[list].elementType.memberDefinitions.getMember('URL')) {
return function (item) {
return {
Id : item.Id,
Title : item.URL,
Modified : item.Modified,
Created : item.Created,
CreatedBy : item.CreatedBy.Name
};
};
}
else {
return function (item) {
return {
Id : item.Id,
Title : item.ContentType,
Modified : item.Modified,
Created : item.Created,
CreatedBy : item.CreatedBy.Name
};
};
}
};
postbox.subscribe("selectedList", function (newValue) {
if (newValue !== '') {
var base = app.context[newValue],
myBase = _.extend({}, base),
// sortExp = function(it){ return it.Modified };
sortExp = 'it.' + orderBy();
if (orderAsc()) {
_.extend(myBase, myBase.orderBy(sortExp));
}
else {
_.extend(myBase, myBase.orderByDescending(sortExp));
}
_.each(includeArray(), function (inc) {
_.extend(myBase, myBase.include(inc));
});
//_.extend(myBase, myBase.include(include()));
_.extend(myBase, myBase.map(chooseMap(newValue)));
_.extend(myBase, myBase.take(take()));
}
myBase.toArray(allItems);
});
// Return public methods
return {
selectedList : selectedList,
take : take,
takeValues : takeValues,
allItems : allItems,
handleAfterRender : handleAfterRender,
showTable : showTable
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment