I have to display a treeview .But it will take much time, that's why I want to load this treeview on demand.At the first I want just display first level, and repeating that level by level.
This is the view
$("#onflycheckboxes").jstree({
json_data: {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = ""
if (node == -1) {
url = "/TreeView/GetCollectionWS/source";
}
else {
nodeId = node.attr('id');
url = "/TreeView/GetCollectionWS/" + nodeId;
}
return url;
},
"type": "POST",
"dataType": "json",
"contentType": "application/json charset=utf-8"
}
},
checkbox: {
real_checkboxes: true,
checked_parent_open: true
},
plugins: ["themes", "json_data", "ui", "checkbox"]
});
this is the controller
public virtual ActionResult GetCollectionWS(string root)
{
int? nodeId = (root == source) ? (int?)null : Convert.ToInt32(root);
Object[] liste = new Object[100];
liste = DSClient.Views.Traitement.getTop(nodeId);
List<TreeViewNode> nodes = new List<TreeViewNode>();
for (int i = 0; (i < liste.Length && liste.ElementAt(i) != null);i++ )
{
bool leaf = false;
nodes.Add(new TreeViewNode()
{
id = Convert.ToString(DSClient.Views.Traitement.GetNodeId(liste.ElementAt(i))),
text = liste.ElementAt(i).Handle,
classes = leaf ? "file" : "folder",
hasChildren = !leaf
});
}
return Json(nodes);
}
when I try a breakpoint on the line return Json(nodes); I remarque that nodes contains
at the first {id=0,text=Collection-10,classes=folder,haChildren=false}
the view display nothing.Please, can any one help me??
public virtual string GetCollectionWS(string id)
{
Object[] liste = new Object[100];
client = new DSServiceClient();
if (id == "source")
{
Collection[] _top = new Collection[100];
client.Open();
_top = client.GetTopCollections();
client.Close();
for (int i = 0; i < _top.Length; i++)
{
DSClient.Controllers.Object obji = new DSClient.Controllers.Object();
obji.Handle = _top[i].Handle;
obji.Name = _top[i].Title;
liste[i] = obji;
}
}
else
{
client = new DSServiceClient();
client.Open();
Tree tree = client.GetTreeView(id);
client.Close();
liste = tree.listObjects;
}
var recursiveObjects = FillRecursive(liste);
string myjsonmodel = new JavaScriptSerializer().Serialize(recursiveObjects);
return myjsonmodel;
}
private static List<RecursiveObject> FillRecursive(Object[] flatObjects)
{
List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();
for (int i = 0; (i < flatObjects.Length && flatObjects.ElementAt(i) != null); i++)
{
recursiveObjects.Add(new RecursiveObject()
{
data = flatObjects.ElementAt(i).Name,
id = flatObjects.ElementAt(i).Handle,
attr = new FlatTreeAttribute { id = flatObjects.ElementAt(i).Handle, selected = false },
children = null,
state = "closed"
});
}
return recursiveObjects;
}
Now I want to send the text and Id of nodes selected to my controller.
<script type="text/javascript">
var divId = [];
var divText = [];
$('#idjstree').value=function GetIDs() {
divId = [];
divText = [];
$("#onflycheckboxes").jstree("get_checked", null, true).each
(function () {
divId.push(this.id);
divText.push($(this).children('a').text());
});
return (divId);
}</script
and this is in the view
#:<div id="onflycheckboxes"></div>
#:<input type="hidden" id="idjstree" name="idjstree" value="" />
but always I get idjstree="" when I do a breakpoint on the post of create.But the function GetIDs() is correct.
What can I do please?
Related
SharePoint Online: I have multiple people picker columns and enter in a number of places people. I get the people OK but it won't update. It says it the entry is undefined. I thought maybe separating each out would work but obviously not. I hope I get some help on this one. What I want to do is to allow users to enter names into where the div entries are and as a people picker. I accomplished that but when you submit the form it says that any entry other than the first is undefined.
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" > < /script>
<script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
<script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
<script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript" src="/_layouts/15/autofill.js"></script>
<script type="text/javascript" src="/_layouts/15/1033/sts_strings.js"></script>
<script type="text/javascript">
var prim5 = 0;var sec4 = 0;var auth5 = 0;
var EorB25 = "";var BorE25 = "";var BorE35 = "";var siteUrl = "https://sp-cloud.kp.org/sites/MedicaidRepository";var cat25 = "";var regimpact = "";var regimpact1 = "";var prim25="";var sec25="";
var auth25="";var s1 = "";var soxD1 = "";var k1 = 'No';var com2 = "";var sDate1 = "";var sSever = "";var kDate1 = "";var finalusersP = [];var finalusers22 = [];var finalusersK = [];var user22 = [];var userK = [];var userP = [];var users22 = [];var usersK = [];var usersP = [];var userPemail = "";var userKemail = "";var user22email = "";
var tDay = new Date();
var dd = tDay.getDate();
var mm = tDay.getMonth()+1;
var yy = tDay.getFullYear();
var sDate = mm+ '/' +dd+ '/' +yy;
$(document).ready(function() {
prim5 = 1;
initializePeoplePickerP('peoplePickerDivP');
registerPPOnChangeEventP($('#peoplePickerDivP'));
});
$(document).ready(function() {
sec5 = 1;
initializePeoplePickerS('peoplePickerDivS');
registerPPOnChangeEventS($('#peoplePickerDivS'));
});
$(document).ready(function() {
auth5 = 1;
initializePeoplePickerK('peoplePickerDivK');
registerPPOnChangeEventK($('#peoplePickerDivK'));
});
function initializePeoplePickerP(peoplePickerElementIdP, UsersP) {
if (typeof(UsersP) == 'undefined') UsersP = null;
console.log('UsersP: ' +UsersP);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdP, null, schema);
}
function initializePeoplePickerS(peoplePickerElementIdS, Users22) {
if (typeof(Users22) == 'undefined') Users22 = null;
console.log('Users22: ' +Users22);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdS, null, schema);
}
function initializePeoplePickerK(peoplePickerElementIdK, UsersK) {
if (typeof(UsersK) == 'undefined') UsersK = null;
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdK, null, schema);
}
function registerPPOnChangeEventP(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
//var ppidTest = picker.toString();
console.log("picker: " +picker);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoP();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventS(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers22').html("");
$('#user22Keys').html("");
$('#user22ProfileProperties').html("");
$('#user22ID').html("");
} else {
setTimeout(function () {
getUserInfoS();
},
100);
}
picker.oldChanged();
}
} else {
//setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventK(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoK();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
// Query the picker for user information.
var userPropertyP = "";
var userPropertyS = "";
var userPropertyK ="";
var userPemail = "";
var i = 0;
var j = 0;
var m = 0;
var keysP = "";
var keysS = "";
var keysK = "";
function getUserInfoP() {
// Get the people picker object from the page.
var peoplePickerP = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivP_TopSpan;
// Get information about all users.
var usersP = peoplePickerP.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersP = new Array();
console.log('Users: ' +usersP);
var ownerP = usersP[0];
for(i = 0; i < usersP.length; i++){
userPemail = usersP[i];
}
console.log('Owner: ' +ownerP);
$("#siteOwenerEmail").val(ownerP.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerP.Key);
$("#siteOwnerName").val(ownerP.DisplayText);
$("#siteOwnerLogin").val(ownerP.Description);console.log('Get People Picker NameP: ' +ownerP.DisplayText);
var userInfo = '';
if(prim5 > 0){
for (var i = 0; i < usersP.length; i++) {
userP = usersP[i];
if(userP !== null){
//userPemail = userP.EntityData.Email;
userPemail = ownerP.DisplayText;
}
console.log("userPemail: " +userPemail);
return userPemail;
console.log('i= ' +i+ 'User= ' +userP);
for (userPropertyP in userP) {
prim25 += userPropertyP + ': ' + userP[userPropertyP] + '<br>';
}
}
$('#resolvedUsers').html(prim25);
// Get user keys.
keysP = peoplePickerP.GetAllUserKeys();
$('#userKeys').html(keysP);
// Get the first user's ID by using the login name.
getUserIdP(usersP[0].Key);
console.log('Initial: ' +prim25);
}
}
function getUserInfoS() {
// Get the people picker object from the page.
var peoplePickerS = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivS_TopSpan;
// Get information about all users.
users22 = peoplePickerS.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersS = new Array();
console.log('Users: ' + users22);
var ownerS = users22[0];
/*for(i = 0; i < usersS.length; j++){
userSemail = usersS[i];
}*/
console.log('Owner: ' +ownerS);
$("#siteOwenerEmail").val(ownerS.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerS.Key);
$("#siteOwnerName").val(ownerS.DisplayText);
$("#siteOwnerLogin").val(ownerS.Description);console.log('Get People Picker NameS: ' +ownerS.DisplayText);
var userInfo = '';
if(sec4 > 0){
for (j = 0; j < users22.length; j++) {
user22 = users22[j];
if(user22 !== null){
//userPemail = userP.EntityData.Email;
user22email = ownerS.DisplayText;
}
for (userPropertyS in user22) {
sec25 += userPropertyS + ': ' + user22[userPropertyS] + '<br>';
}
}
$('#resolvedUsers').html(sec25);
// Get user keys.
keysS = peoplePickerS.GetAllUserKeys();
$('#user22Keys').html(keysS);
// Get the first user's ID by using the login name.
getUserIdS( users22[0].Key);
}
}
function getUserInfoK() {
// Get the people picker object from the page.
var peoplePickerK = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivK_TopSpan;
// Get information about all users.
usersK = peoplePickerK.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersK = new Array();
console.log('Users: ' +usersK);
var ownerK = usersK[0];
/*for(i = 0; i < usersK.length; i++){
userKemail = usersK[i];
}*/
console.log('Owner: ' +ownerK);
$("#siteOwenerEmail").val(ownerK.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerK.Key);
$("#siteOwnerName").val(ownerK.DisplayText);
$("#siteOwnerLogin").val(ownerK.Description);console.log('Get People Picker NameK: ' +ownerK.DisplayText);
var userInfo = '';
if(auth5 > 0){
for (m = 0; m < usersK.length; m++) {
userK = usersK[m];
if(userK !== null){
//userPemail = userP.EntityData.Email;
userKemail = ownerK.DisplayText;
}
for (userPropertyK in userK) {
auth25 += userPropertyK + ': ' + userK[userPropertyK] + '<br>';
}
}
$('#resolvedUsers').html(auth25);
// Get user keys.
keysK = peoplePickerK.GetAllUserKeys();
$('#userKeys').html(keysK);
// Get the first user's ID by using the login name.
getUserIdK(usersK[0].Key);
}
}
// Get the user ID.
function getUserIdP(loginName) {
console.log('Get User ID-P');
var context = new SP.ClientContext.get_current();
this.userP = context.get_web().ensureUser(loginName);
context.load(this.userP);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessP),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessP() {
$('#userId').html(this.userP.get_id());
$("#siteOwenerId").val(this.userP.get_id());
userP = $("#siteOwenerId").val(this.userP.get_id());
}
function getUserIdS(loginName) {
console.log("Get User ID-S");
var context = new SP.ClientContext.get_current();
this.user22 = context.get_web().ensureUser(loginName);
context.load(this.user22);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessS),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessS() {
$('#userId').html(this.user22.get_id());
$("#siteOwenerId").val(this.user22.get_id());
userS = $("#siteOwenerId").val(this.user22.get_id());
}
function getUserIdK(loginName) {
console.log('Get User ID-K');
var context = new SP.ClientContext.get_current();
this.userK = context.get_web().ensureUser(loginName);
context.load(this.userK);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessK),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessK() {
$('#userId').html(this.userK.get_id());
$("#siteOwenerId").val(this.userK.get_id());
userK = $("#siteOwenerId").val(this.userK.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}
function addNewIntake(){
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',updateListItem1);
}
function updateListItem1() {
finalusersP.push(SP.FieldUserValue.fromUser(userP.Key));
finalusers22.push(SP.FieldUserValue.fromUser(user22.Key));
finalusersK.push(SP.FieldUserValue.fromUser(userK.Key));
var clientContext = new SP.ClientContext(siteUrl);
var oList =
clientContext.get_web().get_lists().getByTitle('Issue_Tracker_List');
this.oListItem = oList.addItem();
//console.log('primary person info: ' + finalusersP);
oListItem.set_item('MainContact2',finalusersP);
if(finalusers22 !== ""){
//console.log('secondary person info: ' +finalusers22);
oListItem.set_item('AdditionalContact_x0028_s_x0029_',finalusersS);
}
if(finalusersK !== ""){
oListItem.set_item('ITSupportOwner',finalusersK);
}
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
document.getElementById('main12').style.display="none";
document.getElementById('main22').style.display="block";
setTimeout(CloseDlg, 2000);
}
function CloseDlg() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
I'm using the latest Handsontable version 9.0.0 without any framework and I'm trying to follow the Cell editor developer guide, but I'm at a loss.
My requirement is to show a couple of checkboxes and a text box in one cell (not my idea). My thought was to have the data for the cell be a little json string {"Attr1": true, "Attr2": false} and have a custom renderer/editor that would parse the cell value and set the checkboxes appropriately.
I made a fiddle of it here: http://jsfiddle.net/9k1x4z6b/2/
I created a class for the custom attributes column and a renderer function and set the renderer and editor for the column like this
class CustomAttributesEditor extends Handsontable.editors.BaseEditor {
/**
* Initializes editor instance, DOM Element and mount hooks.
*/
// constructor (props) {
// super(props)
// }
prepare(row, col, prop, td, originalValue, cellProperties) {
// Invoke the original method...
super.prepare(row, col, prop, td, originalValue, cellProperties);
td.innerHTML = '';
this.AttributeNames = ['Attr1', 'Attr2'];
this.ctrls = {};
let parsedValue = JSON.parse(Handsontable.helper.stringify(originalValue));
// Create checkbox controls
for (let i = 0; i < this.AttributeNames.length; i++) {
let AttributeName = this.AttributeNames[i];
let span = document.createElement('span');
span.style.whiteSpace = 'nowrap';
let checkbox = document.createElement('input');
this.ctrls[AttributeName] = checkbox;
checkbox.type = 'checkbox';
if (parsedValue[AttributeName] == 'yes') {
checkbox.checked = true;
}
let label = document.createElement('label');
label.innerHTML = AttributeName;
label.htmlFor = checkbox.id;
span.appendChild(checkbox);
span.appendChild(label);
td.appendChild(span);
td.appendChild(document.createElement('br'));
}
// Create a control that is shown/hidden when the "Attr2" checkbox is toggled
let CustomAttributesAttr3SubDiv = document.createElement('div');
var label = document.createElement('label');
label.innerHTML = "Attr3 supplier:";
CustomAttributesAttr3SubDiv.appendChild(label);
var CustomAttributesAttr3 = document.createElement('input');
if (parsedValue.hasOwnProperty('Attr3')) {
CustomAttributesAttr3.value = parsedValue['Attr3'];
}
this.ctrls['Attr3'] = CustomAttributesAttr3;
this.AttributeNames.push('Attr3');
CustomAttributesAttr3.setAttribute('title', 'Attr3');
CustomAttributesAttr3.style.width = '12em';
CustomAttributesAttr3SubDiv.appendChild(CustomAttributesAttr3);
CustomAttributesAttr3SubDiv.appendChild(document.createElement('br'));
td.appendChild(CustomAttributesAttr3SubDiv);
let Attr2Checkbox = this.ctrls['Attr2'];
//CustomAttributes_ShowHideValueCtrl(Attr2Checkbox);
$(Attr2Checkbox).off('change').on('change', function () {
//CustomAttributes_ShowHideValueCtrl(this); // irrelevant to checkbox problem. function shows Attr3 input when Attr2Checkbox is checked, hides otherwise
});
//preventDefault();
}
getValue(){
// This function returns the set value of the controls
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = null;
if (ctrl.type == 'checkbox'){
if (ctrl.checked == true) {
val = 'yes';
} else {
val = null;
}
} else {
val = ctrl.value;
}
resultDict[FormattedAttributeName] = val;
}
return JSON.stringify(resultDict)
}
setValue(value){
// this function sets the value of the controls to match the data value
let parsedValue = {};
try {
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
} catch (exc) {
for (let i = 0; i < this.AttributeNames.length; i++) {
parsedValue[this.AttributeNames[i]] = 'no';
}
}
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = parsedValue[FormattedAttributeName];
if (ctrl.type == 'checkbox'){
if (val == 'yes'){
ctrl.checked = true;
} else {
ctrl.checked = false;
}
} else {
ctrl.value = val;
}
}
}
saveValue(value, ctrlDown){
super.saveValue(value, ctrlDown);
}
open(){}
close(){}
focus(){}
}
function CustomAttributesRenderer(instance, td, row, col, prop, value, cellProperties) {
// This function shows labels for the checked Attr1-3 values
let AttributeNames = ['Attr1', 'Attr2', 'Attr3'];
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
Handsontable.dom.empty(td);
for (let i = 0; i < AttributeNames.length; i++) {
let AttributeName = AttributeNames[i];
let span = document.createElement('span');
span.style.whiteSpace = 'nowrap';
if (parsedValue[AttributeName] == 'yes') {
let label = document.createElement('label');
label.innerHTML = AttributeName;
span.appendChild(label);
td.appendChild(span);
}
td.appendChild(document.createElement('br'));
}
return td;
}
document.addEventListener("DOMContentLoaded", function () {
var container = document.getElementById('divBFEPartMatrix');
var hot = new Handsontable(container, {
data: [
[JSON.stringify({"Attr1": "yes", "Attr2": "yes", "Attr3": ""})],
[JSON.stringify({"Attr1": "yes", "Attr2": "yes", "Attr3": "somevalue"})],
[JSON.stringify({"Attr1": "no", "Attr2": "no", "Attr3": ""})],
],
columns: [
{renderer: CustomAttributesRenderer, editor: CustomAttributesEditor}
],
rowHeaders: true,
colHeaders: true,
filters: true,
dropdownMenu: true
});
})
The result appears properly, with the cell initially not having checkboxes visible due to the renderer not showing them, then when you click the cell the checkboxes appear. The problem is when you click the checkbox it doesn't toggle.
I presume something in handsontable is re-creating the td and blowing away the state change, but I can't figure out how to prevent that from happening. Is there a fully working custom editor fiddle or something I can reference to figure out how to prevent bubbling?
Any help you can offer would be greatly appreciated.
Well, after another couple days of fiddling around I figured out the full set of code I needed to add to make this work. Posted here in case it helps someone else trying to make a custom cell editor/renderer in handsontable.
class SubstitutePartEditor extends Handsontable.editors.BaseEditor {
init(){
// This function creates the edit div
let div = document.createElement('div');
this.div = div;
div.style.display = 'none';
div.style.position = 'absolute';
div.style.width = 'auto';
div.style.backgroundColor = 'white';
this.AttributeNames = ['The waste bin is part of the waste cart', 'This item includes SUPPLIER tapestry'];
this.ctrls = {};
let cbIsSubstitutePart = document.createElement('input');
this.ctrls['IsSubstitutePart'] = cbIsSubstitutePart;
cbIsSubstitutePart.type = 'checkbox';
div.appendChild(cbIsSubstitutePart);
div.appendChild(document.createElement('br'));
let SubstitutePartSubDiv = document.createElement('div');
SubstitutePartSubDiv.style.display = 'inline-block';
div.appendChild(SubstitutePartSubDiv);
let inputSubstitutePart = document.createElement('textarea');
this.ctrls['SubstitutePart'] = inputSubstitutePart;
inputSubstitutePart.style.width = '220px';
inputSubstitutePart.style.height = '88px';
SubstitutePartSubDiv.appendChild(inputSubstitutePart);
this.hot.rootElement.appendChild(div);
}
UpdateDependentControls(){
let RequiredCtrl = this.ctrls['IsSubstitutePart'];
let Ctrl = this.ctrls['SubstitutePart'];
if (RequiredCtrl.checked == true){
Ctrl.style.display = '';
} else {
Ctrl.style.display = 'none';
}
$(RequiredCtrl).off('change').on('change', function(){
if (RequiredCtrl.checked == true){
Ctrl.style.display = '';
} else {
Ctrl.style.display = 'none';
}
});
}
getValue(){
// This function returns the set value of the controls
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = null;
if (ctrl.type == 'checkbox'){
if (ctrl.checked == true) {
val = 'yes';
} else {
val = null;
}
} else {
val = ctrl.value;
}
resultDict[FormattedAttributeName] = val;
}
return JSON.stringify(resultDict)
}
setValue(value){
// this function sets the value of the controls to match the data value
let parsedValue = {};
try {
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
} catch (exc) {
parsedValue = {
IsSubstitutePart: 'no',
SubstitutePart: "This item requires a waiver from the operator's foreign regulatory agency, <FOREIGN REGULATORY AGENCY NAME>."
};
}
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = parsedValue[FormattedAttributeName];
if (ctrl.type == 'checkbox'){
if (val == 'yes'){
ctrl.checked = true;
} else {
ctrl.checked = false;
}
} else {
ctrl.value = val;
}
}
}
saveValue(value, ctrlDown){
super.saveValue(value, ctrlDown);
}
open() {
this._opened = true;
this.refreshDimensions();
this.UpdateDependentControls();
this.div.style.display = '';
}
refreshDimensions() {
this.TD = this.getEditedCell();
// TD is outside of the viewport.
if (!this.TD) {
this.close();
return;
}
const { wtOverlays } = this.hot.view.wt;
const currentOffset = Handsontable.dom.offset(this.TD);
const containerOffset = Handsontable.dom.offset(this.hot.rootElement);
const scrollableContainer = wtOverlays.scrollableElement;
const editorSection = this.checkEditorSection();
let width = Handsontable.dom.outerWidth(this.TD) + 1;
let height = Handsontable.dom.outerHeight(this.TD) + 1;
let editTop = currentOffset.top - containerOffset.top - 1 - (scrollableContainer.scrollTop || 0);
let editLeft = currentOffset.left - containerOffset.left - 1 - (scrollableContainer.scrollLeft || 0);
let cssTransformOffset;
switch (editorSection) {
case 'top':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.topOverlay.clone.wtTable.holder.parentNode);
break;
case 'left':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.leftOverlay.clone.wtTable.holder.parentNode);
break;
case 'top-left-corner':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode);
break;
case 'bottom-left-corner':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.bottomLeftCornerOverlay.clone.wtTable.holder.parentNode);
break;
case 'bottom':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.bottomOverlay.clone.wtTable.holder.parentNode);
break;
default:
break;
}
if (this.hot.getSelectedLast()[0] === 0) {
editTop += 1;
}
if (this.hot.getSelectedLast()[1] === 0) {
editLeft += 1;
}
const selectStyle = this.div.style;
if (cssTransformOffset && cssTransformOffset !== -1) {
selectStyle[cssTransformOffset[0]] = cssTransformOffset[1];
} else {
Handsontable.dom.resetCssTransform(this.div);
}
const cellComputedStyle = Handsontable.dom.getComputedStyle(this.TD, this.hot.rootWindow);
if (parseInt(cellComputedStyle.borderTopWidth, 10) > 0) {
height -= 1;
}
if (parseInt(cellComputedStyle.borderLeftWidth, 10) > 0) {
width -= 1;
}
selectStyle.height = `${height}px`;
selectStyle.minWidth = `${width}px`;
selectStyle.top = `${editTop}px`;
selectStyle.left = `${editLeft}px`;
selectStyle.margin = '0px';
}
getEditedCell() {
const { wtOverlays } = this.hot.view.wt;
const editorSection = this.checkEditorSection();
let editedCell;
switch (editorSection) {
case 'top':
editedCell = wtOverlays.topOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.select.style.zIndex = 101;
break;
case 'corner':
editedCell = wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.select.style.zIndex = 103;
break;
case 'left':
editedCell = wtOverlays.leftOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.select.style.zIndex = 102;
break;
default:
editedCell = this.hot.getCell(this.row, this.col);
this.div.style.zIndex = '';
break;
}
return editedCell < 0 ? void 0 : editedCell;
}
focus() {
this.div.focus();
}
close() {
this._opened = false;
this.div.style.display = 'none';
}
}
function SubstitutePartRenderer(instance, td, row, col, prop, value, cellProperties) {
// This function draws the multi checkboxes for the SubstitutePart input field
// Note: if AttributeNames changes you must also update BFEPartMatrix_Edit.ascx line ~240 to match (<- this is where the data is saved)
//Handsontable.renderers.HtmlRenderer.apply(this, arguments);
let parsedValue = {};
try {
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
} catch {
// nothing to do
}
Handsontable.dom.empty(td);
let div = document.createElement('div');
//div.style.whiteSpace = 'nowrap';
div.style.display = 'block';
td.appendChild(div);
if (parsedValue.hasOwnProperty('IsSubstitutePart')) {
if (parsedValue.IsSubstitutePart == 'yes') {
} else {
td.innerHTML = 'N/A';
return;
}
} else {
td.innerHTML = 'N/A';
return;
}
let SubstitutePartSubDiv = document.createElement('div');
SubstitutePartSubDiv.style.display = 'inline-block';
div.appendChild(SubstitutePartSubDiv);
// text area
let inputSubstitutePart = document.createElement('label');
inputSubstitutePart.innerHTML = parsedValue['SubstitutePart'].escape();
inputSubstitutePart.style.width = '220px';
inputSubstitutePart.style.height = '88px';
SubstitutePartSubDiv.appendChild(inputSubstitutePart);
return td;
}
then set the render and editor of the hot column like this
columns: [
{renderer: CustomAttributesRenderer, editor: CustomAttributesEditor}
],
I want to have ActionLink "Details", "Edit" and "Delete" according to ID with an Ajax list, I managed to get my list out with datatable without having my columns in the script as you can see in my code, I would like to add the 3 links at the end of my table.
This is my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
var QueryString = HttpContext.Request.QueryString;
var orderBy = QueryString.Get("order[0][column]");
var orderByDir = QueryString.Get("order[0][dir]");
var search = QueryString.Get("search[value]");
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null) {
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{orderBy}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "1_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "1_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "2_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "2_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "0_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = lstData
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
This is my ajax call:
$(document).ready(function ()
{
$("#registrationTable").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
}
});
});
And this is my html for the table:
<table id="registrationTable" class="table table-striped dt-responsive display datatable dtr-inline" role="grid" aria-describedby="example-1_info">
<thead>
<tr>
<th>
ID
</th>
<th>
#Resource.FullName
</th>
<th>
#Resource.Email
</th>
<th class="sorting_desc_disabled sorting_asc_disabled">
#Resource.BirthDate
</th>
#*<th>
Edit
</th>
<th>
Delete
</th>*#
</tr>
</thead>
</table>
I found the solution, my controller changes a little bit, so here is my new code:
In my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
string orderByDir, search;
int orderByIdx;
List<string> cols = ExtractDataSortAndFilter(out orderByIdx, out orderByDir, out search);
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null)
{
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{cols[orderByIdx]}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "FullName_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "FullName_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "Email_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "Email_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "ID_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = new List<RegistrationsList>();
if (length > -1)
{
data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
}
else
{
data = query.Skip((int)start).ToList<RegistrationsList>();
}
/*var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}*/
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = data
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
private List<string> ExtractDataSortAndFilter(out int orderByIdx, out string orderByDir, out string search)
{
List<string> cols;
var QueryString = HttpContext.Request.QueryString;
cols = new List<string>();
string colName = null, colNamePath = "";
int colIdx = 0;
do
{
colNamePath = "columns[" + colIdx + "][data]";
colName = QueryString.Get(colNamePath);
cols.Add(colName);
colIdx++;
} while (colName != null);
string orderBy = QueryString.Get("order[0][column]");
orderByDir = QueryString.Get("order[0][dir]");
search = QueryString.Get("search[value]");
orderByIdx = orderBy == null ? 0 : int.Parse(orderBy);
orderByDir = orderByDir == null ? "asc" : orderByDir;
search = search == null ? "" : search;
return cols;
}
and this is my script:
$(document).ready(function () {
$("#registrationTable").DataTable({
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
},
"columns": [
{
data: null,
title: "<input type=\"checkbox\" id=\"btnSelAllStudents\">",
render: function (data, type, row, meta) {
return '<input type="checkbox" id="cbxRegStudent_' + row.ID + '" value="' + row.ID + '">';
},
targets: "no-sort",
orderable: false
},
{ data: "ID", title: "ID" },
{ data: "FullName", title: "#Resource.FullName" },
{ data: "Email", title: "#Resource.Email" },
{ data: "BirthDate", title: "#Resource.BirthDate" },
{
data: null, title: "Actions",
render: function (data, type, row, meta) {
/*return '<input type="button" class="btn-print printrec" id="' + row.ID + '" value="Print"/>';*/
return '#Resource.Profile | #Resource.Edit';
},
targets: "no-sort",
orderable: false
}
],
order: [],
});
$("#btnSelAllStudents").on("change", function (e) {
$("input[id^='cbxRegStudent_']").prop("checked", $(this).prop("checked"));
});
$('#registrationTable').on('processing.dt', function (e, settings, processing) {
$("#btnSelAllStudents").prop("checked", false);
}).dataTable();
});
I'm importend in my workspace, a project build in appcelerator.
So I have some error like this:
If I open any file, I have this situation:
I don't know, how to fix this.
So this is my plugin.js
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
var _optionManager = require("./file/options/option-manager");
var _optionManager2 = _interopRequireDefault(_optionManager);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _store = require("../store");
var _store2 = _interopRequireDefault(_store);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _assign = require("lodash/assign");
var _assign2 = _interopRequireDefault(_assign);
var _clone = require("lodash/clone");
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint max-len: 0 */
var GLOBAL_VISITOR_PROPS = ["enter", "exit"];
var Plugin = function (_Store) {
(0, _inherits3.default)(Plugin, _Store);
function Plugin(plugin, key) {
(0, _classCallCheck3.default)(this, Plugin);
var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this));
_this.initialized = false;
_this.raw = (0, _assign2.default)({}, plugin);
_this.key = key;
_this.manipulateOptions = _this.take("manipulateOptions");
_this.post = _this.take("post");
_this.pre = _this.take("pre");
_this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {});
return _this;
}
Plugin.prototype.take = function take(key) {
var val = this.raw[key];
delete this.raw[key];
return val;
};
Plugin.prototype.chain = function chain(target, key) {
if (!target[key]) return this[key];
if (!this[key]) return target[key];
var fns = [target[key], this[key]];
return function () {
var val = void 0;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var fn = _ref;
if (fn) {
var ret = fn.apply(this, args);
if (ret != null) val = ret;
}
}
return val;
};
};
Plugin.prototype.maybeInherit = function maybeInherit(loc) {
var inherits = this.take("inherits");
if (!inherits) return;
inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits");
this.manipulateOptions = this.chain(inherits, "manipulateOptions");
this.post = this.chain(inherits, "post");
this.pre = this.chain(inherits, "pre");
this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]);
};
/**
* We lazy initialise parts of a plugin that rely on contextual information such as
* position on disk and how it was specified.
*/
Plugin.prototype.init = function init(loc, i) {
if (this.initialized) return;
this.initialized = true;
this.maybeInherit(loc);
for (var key in this.raw) {
throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
}
};
Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) {
for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var key = _ref2;
if (visitor[key]) {
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.");
}
}
_babelTraverse2.default.explode(visitor);
return visitor;
};
return Plugin;
}(_store2.default);
exports.default = Plugin;
module.exports = exports["default"];
How can I fixed it?
import syntax is from ECMAScript 6 - which is yet to be added in the Appcelerator Studio.
https://jira.appcelerator.org/browse/TISTUD-6927
As example only.
I have:
var ListingModel = require("~/shared/view-models/listing-view-model");
function listing10(){
var Listing = new ListingModel.ListingViewModel();
Listing.horizontalAddData('10');
frameModule.topmost().navigate("/views/listing/list");
}
function listing20(){
var Listing = new ListingModel.ListingViewModel();
Listing.horizontalAddData('20');
frameModule.topmost().navigate("/views/listing/list");
}
function listing50(){
var Listing = new ListingModel.ListingViewModel();
Listing.horizontalAddData('50');
frameModule.topmost().navigate("/views/listing/list");
}
exports.listing10 = listing10;
exports.listing20 = listing20;
exports.listing50 = listing50;
When i now tap on event listing10 i receive all information which i require.
But, when i now tap event listing20 i become back the information from listing10 and listing20. That means, the the new object isnt a new object with cleared data?
Question: How i must call the new ListingModel.ListingViewModel(); so that i really become back a new, clear ListingViewModel Object?
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Model = require('~/shared/view-models/view-model');
var ListingViewModel = (function (_super) {
__extends(ListingViewModel, _super);
function ListingViewModel() {
_super.apply(this, arguments);
}
var params = {start: 0 , limit: 7};
var page = 0;
var _listRequested = new virtualArray.VirtualArray(7);
_listRequested.loadSize = params.limit;
var _fetch = new f.fetchHelper();
var loading = 0;
var that=this;
var indexes = [];
var horizontalindex = [];
var fetchlist = [];
var listing ='';
Object.defineProperty(ListingViewModel.prototype, "list", {
get: function () {
return _listRequested;
},
enumerable: true,
configurable: true
});
ListingViewModel.prototype.horizontalAddData = function(val) {
listing = val;
that.loadItems();
};
loadItems = function (args) {
if(loading == 1) return;
loading = 1;
fetchlist = [];
var url = config.apiUrl + '?t=listing'
+ '&listing=' + list
+ '&start=' + params.start
+ '&limit=' + params.limit;
_fetch.getJSON(url).then(function (res) {
try {
for (var i = 0; i < res.list.length; i++) {
var am = new Model.Model(res.list[i]);
fetchlist.push(am);
}
_listRequested.length = _listRequested.length + fetchlist.length;
_listRequested.load(params.start, fetchlist);
} catch (e) {
alert('error' + e);
}
params.start = params.start + params.limit;
loading = 0;
});
};
return ListingViewModel;
})(observable.Observable);
exports.ListingViewModel = ListingViewModel;