Undefined variable in modularized script - javascript

I've been working at making this script more modularized toady, and I am running into an error. Am I ordering my logic incorrectly?
Error Msg
Uncaught ReferenceError: accountId is not defined
Related Script Line
_.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);
});
Script
var debug = 0;
function paramsStr(p) {
var first = true;
var s = '';
_.each(p,function (value,key) {
if (!value) {
return;
}
if (first) {
s += '?';
first = false;
} else {
s += '&';
}
s += key+'='+value;
});
return s;
};
function parseReport(data)
{
var split = data.split('\n');
var results = [];
_.each(split,function (row) {
if (!row || row == "") {
return;
}
var myRow = JSON.parse(row);
myRow.timestamp = moment.utc(myRow.timestamp);
results.push(myRow);
});
return results;
}
function loadReport(report,granularity,startTime,endTime) {
if (debug && _.has(mock.reports,report) && _.has(mock.reports[report],granularity)) {
return jQuery.Deferred().resolve(parseReport(mock.reports[report][granularity])).promise();
}
var params = {
granularity : granularity
};
if (startTime) {
params['start-time'] = startTime.toISOString();
}
if (endTime) {
params['end-time'] = endTime.toISOString();
}
var url = '//analytics.locuslabs.com/api/reports/'+report+paramsStr(params);
return $.ajax({
url : url,
dataType : 'text'
}).then(function (data) {
return parseReport(data);
});
};
$(document).ready(function () {
var placeholder = $(".graph");
var oneMonth = moment().utc().subtract(1, 'months');
var twoWeeks = moment().utc().subtract(2, 'weeks');
//Function call to get the current time
function dateNow(target,timeFormat){
$(placeholder).siblings(target).text(moment(Date.now()).format(timeFormat));
}
function pollData(apiRoot,increment,startDate,label){
loadReport(apiRoot,increment, startDate).then(function (results) {
var totals = [];
var accounts = {};
_.each(results, function (result) {
totals.push([
result.timestamp.valueOf(),
result.data.total
]);
_.each(result.data.accounts, function (account, accountId) {
if (!_.has(accounts, accountId)) {
accounts[accountId] = {
label: account.account.name,
data: []
};
}
accounts[accountId].data.push([
result.timestamp.valueOf(),
account.total
]);
});
_.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);
});
});
var data = [{
data: totals,
label: label
}];
_.each(accounts, function (account) {
data.push(account);
});
$(this > ".graph").plot(data, {
grid: {
hoverable: true
},
tooltip: {
show: true
},
xaxis: {
mode: "time"
},
yaxis: {
axisLabel: label
},
legend: {
container: $(this > ".legend")
},
selection: {
mode: "x"
}
});
});
// Reload function within pollData function
document.getElementById(apiRoot + "-reload").addEventListener("click", function() {
pollData(apiRoot,increment,startDate,label);
dateNow(".status","M/D/YYYY H:mm Z");
}, false);
}
//Load Reports
pollData('total-installs', 'day', oneMonth, "Total Installs");
pollData('installs', 'hour', twoWeeks, "Installs (by hour)");
pollData('sessions', 'day', twoWeeks, "Sessions");
pollData('sessions-length', 'day', twoWeeks, "Session Length");
// Selection Feature
// TODO: Add Zoom to selection
// TODO: Overview of Available Data when zoomed.
placeholder.bind("plotselected", function (event, ranges) {
var begin = ranges.xaxis.from.valueOf();
var end = ranges.xaxis.to.valueOf();
$(this).siblings(".selection").text(moment(begin).format("M/D/YYYY H:mm Z") + " to " + moment(end).format("M/D/YYYY H:mm Z"));
/*
var zoom = $("#zoom").prop("checked");
if (zoom) {
$.each(plot.getXAxes(), function(_, axis) {
var opts = axis.options;
opts.min = ranges.xaxis.from;
opts.max = ranges.xaxis.to;
});
plot.setupGrid();
plot.draw();
plot.clearSelection();
}
*/
});
// Update on Initial Poll
// TODO: Ask for location and provide local time.
dateNow(".status","M/D/YYYY H:mm Z");
});

You have no accountId parameter in your function
function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);

Related

Getting Error on Two Events happening on same time

I'm having the activiti Bpmn file, in that there is having transition of task. While transition I need to create the due date for that new task. my problem is due date and new task happening on same time. because of that I'm getting error.
onClose: function (date) {
if (valid) {
date = Date.parse(date);
if (oldDate !== date) {
var tasks = getSet(context, 'task') || getSet(context, 'tasks'),
trans = Ember.get(context, 'transition') || Ember.get(context, 'propertyMap.transition'),
requestData = [];
if (!tasks.length) {
resolve();
return;
}
if (!trans) {
trans = 'Done';
}
tasks.forEach(function (task) {
requestData.push({ name: 'id', value: (Ember.get(task, 'id') || Ember.get(task, 'currentTask.id') )});
requestData.push({ name: 'transition', value: trans || '' });
});
if (context.get('serviceParams')) {
Object.asAjaxData(context.get('serviceParams')).forEach(function (param) {
requestData.push(param);
});
}
return (Core.services({
type: 'post',
service: 'workflow/task/transition',
data: requestData,
json: true
})
.done(function (res) {
Core.Action('Core:updateTask', context, { dtDue: date });
Core.model.ingestResources(res);
var inspected = Core.controller.detailsObject,
wf = res.workflows || {};
if (inspected) {
Object.keys(wf).forEach(function (w) {
var hist = wf[w].historicalTaskIds;
if (hist.contains(inspected.currentTaskId)) {
inspected.set('currentTaskId', wf[w].openTaskIds[0]);
}
});
}
resolve();
})
.fail(function (xhr, status, error) {
Core.Error.show(error);
})
.always(function () {
tasks.forEach(function (task) {
if (Ember.get(task, 'isClip')) {
Core.model.clip.clear();
}
});
var wfController = Core.Tab.Workflow.getController();
var sel = wfController.get('selection');
wfController.reloadResultSet();
var rs = wfController.get('resultSet');
rs && rs.done(function () {
var s = Ember.Set.create();
rs.get('content').forEach(function (item) {
if (!item) { return; }
s.addObject(item);
});
sel.forEach(function (item) {
if (!s.contains(item)) {
sel.remove(item);
}
});
});
sel.clear();
resolve(tasks);
})
);
}
}
}
In that Core.Action('Core:updateTask', context, { dtDue: date }); is using for updating the duedate. If I use on the top If statement Due Date is updated, but Transistion is not happening. If I'm using on the done function, the transistion is happened and moved to the new Task Id. Because of that it searching Task Id and showing error.
Please provide me suggestion on this. I need to create both the Transistion and meanwhile update the date.

Customizing easyAutoComplete

var options = {
url: function (phrase) {
return "location/autoComplete?key=" + phrase;
},
getValue: "cityName",
template: {
type: "custom",
method: function (value, item) {
return value + ", " + item.stateName;
}
},
list: {
onClickEvent: function () {
var selectedLongitude = $("#autoCompleteSearch").getSelectedItemData().longitude;
var selectedLatitude = $("#autoCompleteSearch").getSelectedItemData().latitude;
userPos = {
lat: Number(selectedLatitude),
lng: Number(selectedLongitude)
};
map.setCenter(userPos);
map.setZoom(17)
},
showAnimation: {
type: "fade", //normal|slide|fade
time: 400,
callback: function () {
}
},
hideAnimation: {
type: "slide", //normal|slide|fade
time: 400,
callback: function () {
}
}
}
};
This is the code I am using right now to fetch a remote webservice data. Now I need to get the data and remove the duplicate "city names". Also I need to show "Data not available" or some custom method when there is no data from the webservice. I am kind of stuck. Would be great if someone could point me on how to achieve this.
You can get rid of duplicates using a helper function:
function removeDuplicates(input) {
if (!input) { //Falsy input
return input;
}
var isArray = Array.isArray(input) ? [] : {};
var items = [];
var output = {};
for (var key in input) {
if (items.indexOf(input[key]) < 0) {
items.push(input[key]);
if (!isArray) {
output[key] = input[key];
}
}
}
return isArray ? items : output;
}
You can show your custom text if Array.isArray(input) ? (input.length === 0) : (Object.keys(input).length === 0 && input.constructor === Object).

printing all records using only one alert

I have the following code with the JSFiddle for the same here:
var result = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
$.each(result, function(i, item) {
alert(result[i].PageName);
});
In order to see all the results, I have to click Ok in alert window two times. How can I display the contents using one alert only?
//f1.js ---
var PatientReviewPage = (function () {
var cls = function () { }
var self = cls.prototype;
self.urlKey = "showmrn";
self.getData = function (mrn_) {
/*
if (isEmpty(mrn_)) { alert("Invalid mrn in getData()"); return false; }
// Lookup the AJAX web service URL
var url = regman.getWebServiceURL(self.urlKey);
if (isEmpty(url)) { alert("Invalid URL in getData()"); return false; }
var ajaxRequest = jQuery.ajax({
//beforeSend: TODO: show spinner!
data: {
registry_id: regman.registry.id,
mrn: mrn_
},
dataType: "json",
method: "GET",
url: url
})*/
//Some code related to ajax reques
this.done(function (data_, textStatus_, jqXHR_) {
// Validate the web service and retrieve the status.
if (typeof (data_) === "undefined" || data_ === null) {
alert("Invalid data returned from web service");
return false;
}
if (isEmpty(data_.webservice_status) || isEmpty(data_.webservice_status.status)) {
alert("Invalid web service status");
return false;
}
if (data_.webservice_status.status != "SUCCESS") {
alert(data_.webservice_status.message);
return false;
}
self.processdataDocuments(data_.data_document_list);
});
this.fail(function (jqXHR_, textStatus_, errorThrown_) {
alert("Error in getData(): " + errorThrown_);
return false;
});
};
// Initialize the page
self.initialize = function () {
var mrn = regman.selectedData["mrn"];
if (isEmpty(mrn)) {
alert("Invalid MRN provided by calling page");
return false;
}
self.getData(mrn);
};
self.processdataDocuments = function (collection_) {
if (isEmpty(collection_) || collection_.length < 1) {
// Populate the count and exit
jQuery("#nlpDocumentCount").html("(0)");
return true;
}
var source =
{
localdata: collection_,
datatype: "array"
};
var dataAdapter = new $.jqx.dataAdapter(source, {
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
$("#nlpDocumentPanel").jqxGrid(
{
source: dataAdapter,
width: '1000',
height: 150,
columns: [
{
text: 'Type', datafield: 'nc_type'
},
{
text: 'SubType', datafield: 'nc_subtype'
},
{
text: 'Concept', datafield: 'concept_text'
},
{
text: 'Date', datafield: 'nc_dos'
}
]
});
// For getting the contents of a row, I am using jqxgrid approach as mentioned in their doc here :
// http://www.jqwidgets.com/getting-the-clicked-grid-row/
$("#nlpDocumentPanel").on('rowclick', function (event) {
var row = event.args.rowindex;
var datarow = $("#nlpDocumentPanel").jqxGrid('getrowdata', row);
response = JSON.stringify(datarow, null, 10)
//alert(jsonStringify); // This alert displays the JSON data in a formatted manner
var obj = jQuery.parseJSON(response);
//alert("display Subtype "+obj.nc_subtype) // Works fine
self.mySubtype = obj.nc_subtype;
});
};
//I added this line for the demo to show 'f2' accessing this property from 'f1'. You should remove it if copying this code into your application
self.mySubtype = "Foo";
return cls;
})();
var f1 = new PatientReviewPage();
//f2.js ---
var DocumentDetailsDialog = (function () {
var cls = function () { }
var self = cls.prototype;
alert(f1.mySubtype);
/*this.getData = function (IDNumber_) {
// some code will be here
var ajaxRequest = jQuery.ajax({
// some code will be here
})
.done(function (data_, textStatus_, jqXHR_) {
// some code will be here
})
.fail(function (jqXHR_, textStatus_, errorThrown_) {
// some code will be here
});
};*/
return cls;
})();
var f2 = new DocumentDetailsDialog();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use map() and join() and return string with page names.
var result = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
var r = result.map(function(e) {
return e.PageName;
}).join(' ');
alert(r);
Build a string with the results and alert the string:
alert(result.map( _ => _.PageName).join(', '))

Angularjs Directives Scope Issue

I am having trouble with a directive. My model updates with data that is being loaded by a http call. Without the call the service the directive works correctly.
I have a directive called validationmessagefor that listens to when a field has been marked to have an error. When it has an error it displays the error message.
The plunker attached Plnkr
How do I get the directive to respond or load correctly against the model when using services to load data?
angular.module('dataApp', ['servicesModule', 'directivesModule'])
.controller('dataCtrl', ['$scope', 'ProcessService', 'ValidationRuleFactory', 'Validator',
function($scope, ValidationRuleFactory, Validator, ProcessService) {
$scope.viewModel = {};
var FormFields = {};
// we would get this from the meta api
ProcessService.getProcessMetaData().then(function(data) {
FormFields = {
Name: "Course",
Fields: [{
type: "text",
Name: "name",
label: "Name",
data: "",
required: true,
ruleSet: "personFirstNameRules"
}, {
type: "text",
Name: "description",
label: "Description",
data: "",
required: true,
ruleSet: "personEmailRules"
}]
};
$scope.viewModel = FormFields;
ProcessService.getProcessRuleData().then(function(data) {
var genericErrorMessages = {
required: 'Required',
minlength: 'value length must be at least %s characters',
maxlength: 'value length must be less than %s characters'
};
var rules = new ValidationRuleFactory(genericErrorMessages);
$scope.viewModel.validationRules = {
personFirstNameRules: [rules.isRequired(), rules.minLength(3)],
personEmailRules: [rules.isRequired(), rules.minLength(3), rules.maxLength(7)]
};
$scope.viewModel.validator = new Validator($scope.viewModel.validationRules);
});
});
var getRuleSetValuesMap = function() {
return {
personFirstNameRules: $scope.viewModel.Fields[0].data,
personEmailRules: $scope.viewModel.Fields[1].data
};
};
$scope.save = function() {
$scope.viewModel.validator.validateAllRules(getRuleSetValuesMap());
if ($scope.viewModel.validator.hasErrors()) {
$scope.viewModel.validator.triggerValidationChanged();
return;
} else {
alert('person saved in!');
}
};
}
]);
The directive to display the custom error message
(function(angular, $) {
angular.module('directivesModule')
.directive('validationMessageFor', [function() {
return {
restrict: 'A',
scope: {eID: '#val'},
link: function(scope, element, attributes) {
//var errorElementId = attributes.validationMessageFor;
attributes.$observe('validationMessageFor', function(value) {
errorElementId = value;
if (!errorElementId) {
return;
}
var areCustomErrorsWatched = false;
var watchRuleChange = function(validationInfo, rule) {
scope.$watch(function() {
return validationInfo.validator.ruleSetHasErrors(validationInfo.ruleSetName, rule.errorCode);
}, showErrorInfoIfNeeded);
};
var watchCustomErrors = function(validationInfo) {
if (!areCustomErrorsWatched && validationInfo && validationInfo.validator) {
areCustomErrorsWatched = true;
var validator = validationInfo.validator;
var rules = validator.validationRules[validationInfo.ruleSetName];
for (var i = 0; i < rules.length; i++) {
watchRuleChange(validationInfo, rules[i]);
}
}
};
// get element for which we are showing error information by id
var errorElement = $("#" + errorElementId);
var errorElementController = angular.element(errorElement).controller('ngModel');
var validatorsController = angular.element(errorElement).controller('validator');
var getValidationInfo = function() {
return validatorsController && validatorsController.validationInfoIsDefined() ? validatorsController.validationInfo : null;
};
var validationChanged = false;
var subscribeToValidationChanged = function() {
if (validatorsController.validationInfoIsDefined()) {
validatorsController.validationInfo.validator.watchValidationChanged(function() {
validationChanged = true;
showErrorInfoIfNeeded();
});
// setup a watch on rule errors if it's not already set
watchCustomErrors(validatorsController.validationInfo);
}
};
var getErrorMessage = function(value) {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return '';
}
var errorMessage = "";
var errors = validationInfo.validator.errors[validationInfo.ruleSetName];
var rules = validationInfo.validator.validationRules[validationInfo.ruleSetName];
for (var errorCode in errors) {
if (errors[errorCode]) {
var errorCodeRule = _.findWhere(rules, {errorCode: errorCode});
if (errorCodeRule) {
errorMessage += errorCodeRule.validate(value).errorMessage;
break;
}
}
}
return errorMessage;
};
var showErrorInfoIfNeeded = function() {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return;
}
var needsAttention = validatorsController.ruleSetHasErrors() && (errorElementController && errorElementController.$dirty || validationChanged);
if (needsAttention) {
// compose and show error message
var errorMessage = getErrorMessage(element.val());
// set and show error message
element.text(errorMessage);
element.show();
} else {
element.hide();
}
};
subscribeToValidationChanged();
if (errorElementController)
{
scope.$watch(function() {
return errorElementController.$dirty;
}, showErrorInfoIfNeeded);
}
scope.$watch(function() {
return validatorsController.validationInfoIsDefined();
}, subscribeToValidationChanged());
});
}
};
}]);
})(angular, $);

Avoid page flickering when updating a YUI DataTable

I am using jlinq a library for extending linq to json and hence i filter my json data. Consider i have a json data that draws a yui datatable on page load with 100 rows. I am doing a clientside filter which will reduce my json data and i am now redrawing the same datatable. What happens is it works pretty well but with an annoying flickering effect...
I call the below method from onkeyup event of the filter textbox,
function showusersfilter(txt) {
var jsondata = document.getElementById("ctl00_ContentPlaceHolder1_HfJsonString").value;
jsondata = jQuery.parseJSON(jsondata);
var results = jLinq.from(jsondata.Table)
.startsWith("name", txt)
.select();
var jsfilter = { "Table": results };
var myColumnDefs = [
{ key: "userid", label: "UserId", hidden: true },
{ key: "name", label: "Name", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC} },
{ key: "designation", label: "Designation" },
{ key: "phone", label: "Phone" },
{ key: "email", label: "Email" },
{ key: "role", label: "Role", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC} },
{ key: "empId", label: "EmpId" },
{ key: "reportingto", label: "Reporting To", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC} },
{ key: "checkbox", label: "", formatter: "checkbox", width: 20 }
];
var jsonObj = jsfilter;
var target = "datatable";
var hfId = "ctl00_ContentPlaceHolder1_HfId";
generateDatatable(target, jsonObj, myColumnDefs, hfId);
}
My textbox looks
<asp:TextBox ID="TxtUserName" runat="server" CssClass="text_box_height_14_width_150" onkeyup="showusersfilter(this.value);"></asp:TextBox>
and my generatedatatable function,
function generateDatatable(target, jsonObj, myColumnDefs, hfId) {
var root;
for (key in jsonObj) {
root = key; break;
}
var rootId = "id";
if (jsonObj[root].length > 0) {
for (key in jsonObj[root][0]) {
rootId = key; break;
}
}
YAHOO.example.DynamicData = function() {
var myPaginator = new YAHOO.widget.Paginator({
rowsPerPage: 25,
template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
rowsPerPageOptions: [10, 25, 50, 100],
pageLinks: 10
});
// DataSource instance
var myDataSource = new YAHOO.util.DataSource(jsonObj);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = { resultsList: root, fields: new Array() };
myDataSource.responseSchema.fields[0] = rootId;
for (var i = 0; i < myColumnDefs.length; i++) {
myDataSource.responseSchema.fields[i + 1] = myColumnDefs[i].key;
}
// DataTable configuration
var myConfigs = {
sortedBy: { key: myDataSource.responseSchema.fields[1], dir: YAHOO.widget.DataTable.CLASS_ASC }, // Sets UI initial sort arrow
paginator: myPaginator
};
// DataTable instance
var myDataTable = new YAHOO.widget.DataTable(target, myColumnDefs, myDataSource, myConfigs);
myDataTable.resizeHack = function()
{ this.getTbodyEl().parentNode.style.width = "100%"; }
myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
myDataTable.subscribe("checkboxClickEvent", function(oArgs) {
var hidObj = document.getElementById(hfId);
var elCheckbox = oArgs.target;
var oRecord = this.getRecord(elCheckbox);
var id = oRecord.getData(rootId);
if (elCheckbox.checked) {
if (hidObj.value == "") {
hidObj.value = id;
}
else {
hidObj.value += "," + id;
}
}
else {
hidObj.value = removeIdFromArray("" + hfId, id);
}
});
myPaginator.subscribe("changeRequest", function() {
if (document.getElementById(hfId).value != "") {
if (document.getElementById("ConfirmationPanel").style.display == 'block') {
document.getElementById("ConfirmationPanel").style.display = 'none';
}
document.getElementById(hfId).value = "";
}
return true;
});
myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
return {
ds: myDataSource,
dt: myDataTable
};
} ();
}
EDIT:
I even used a delay on the keyup event still the flickering occurs,
var timer;
function chk_me(){
clearTimeout(timer);
timer = setTimeout(function validate(){ showusersfilter(document.getElementById("ctl00_ContentPlaceHolder1_TxtUserName").value);}, 1000);
}
Why do you create a new dataTable each time you filter your data ? You do not need this task. Just supply The filtered data to its dataTable by using sendRequest method of its dataSource
I have create this jsonObject To simulate filtered data
var jsonObject = {
"root":[
{id:"5", userid:"1", name:"ar", designation:"1programmer", phone:"15484-8547", email:"1arthurseveral#yahoo.com.br", role:"1developer", empId:"1789", reportingto:"116"},
{id:"5", userid:"2", name:"br", designation:"2programmer", phone:"25484-8547", email:"2arthurseveral#yahoo.com.br", role:"2developer", empId:"2789", reportingto:"216"},
{id:"5", userid:"3", name:"cr", designation:"3programmer", phone:"35484-8547", email:"3arthurseveral#yahoo.com.br", role:"3developer", empId:"3789", reportingto:"316"},
{id:"5", userid:"4", name:"dr", designation:"4programmer", phone:"45484-8547", email:"4arthurseveral#yahoo.com.br", role:"4developer", empId:"4789", reportingto:"416"},
{id:"5", userid:"5", name:"er", designation:"5programmer", phone:"55484-8547", email:"5arthurseveral#yahoo.com.br", role:"5developer", empId:"5789", reportingto:"516"}
],
"another":[
{id:"5", userid:"5", name:"er", designation:"5programmer", phone:"55484-8547", email:"5arthurseveral#yahoo.com.br", role:"5developer", empId:"5789", reportingto:"516"},
{id:"5", userid:"4", name:"dr", designation:"4programmer", phone:"45484-8547", email:"4arthurseveral#yahoo.com.br", role:"4developer", empId:"4789", reportingto:"416"},
{id:"5", userid:"3", name:"cr", designation:"3programmer", phone:"35484-8547", email:"3arthurseveral#yahoo.com.br", role:"3developer", empId:"3789", reportingto:"316"},
{id:"5", userid:"2", name:"br", designation:"2programmer", phone:"25484-8547", email:"2arthurseveral#yahoo.com.br", role:"2developer", empId:"2789", reportingto:"216"},
{id:"5", userid:"1", name:"ar", designation:"1programmer", phone:"15484-8547", email:"1arthurseveral#yahoo.com.br", role:"1developer", empId:"1789", reportingto:"116"}
]
};
When initializing
(function() {
var Yutil = YAHOO.util,
Ywidget = YAHOO.widget
DataTable = Ywidget.DataTable,
Paginator = Ywidget.Paginator,
DataSource = Yutil.DataSource;
YAHOO.namespace("_3657287"); // QUESTION ID - SEE URL
var _3657287 = YAHOO._3657287;
/**
* paginator
*/
var paginator = new Paginator({
rowsPerPage:25,
template:Paginator.TEMPLATE_ROWS_PER_PAGE,
rowsPerPageOptions:[10, 25, 50, 100],
pageLinks:10
});
/**
* dataSource
*
* As you have static data, I pass an empty "jsonObject" to its constructor
*/
var dataSource = new DataSource({root:[]});
dataSource.responseType = DataSource.TYPE_JSON;
dataSource.responseSchema = {resultsList:"root", fields:[]};
var columnSettings = [
{key:"userid", label:"UserId"},
{key:"name", label:"Name"},
{key:"designation", label:"Designation"},
{key:"phone", label:"Phone"},
{key:"email", label:"Email"},
{key:"role", label:"Role"},
{key:"empId", label:"EmpId"},
{key:"reportingto", label:"Reporting To"}
];
dataSource.responseSchema.fields[0] = "id";
for (var i = 0; i < columnSettings.length; i++) {
dataSource.responseSchema.fields[i + 1] = columnSettings[i].key;
}
/**
* Notice initialLoad equal To false (I suppose your dataTable IS NOT pre-populated)
*/
var dataTableSettings = {
paginator:paginator,
initialLoad:false
};
/**
* dataTable
*
* Notice IT IS STORED in the namespace YAHOO._3657287
*/
_3657287.dataTable = new DataTable("container", columnSettings, dataSource, dataTableSettings);
})();
Now when you want to filter your data, do as follows (Notice sendRequest method)
var i = 0;
YAHOO.util.Event.addListener("reload", "keyup", function(e) {
YAHOO._3657287.dataTable.getDataSource().sendRequest(null, {
success:function(request, response, payload) {
/**
* initializeTable method clear any data stored by The datatable
*/
this.initializeTable();
if(i === 0) {
this.getRecordSet().setRecords(jsonObject["root"], 0);
i++;
} else {
this.getRecordSet().setRecords(jsonObject["another"], 0);
i--;
}
this.render();
},
scope:YAHOO._3657287.dataTable,
argument:null
});
});
You can see here. It works fine!
But if the effect appears again (Notice i am just using relevant part - Nor special feature Nor something else) can occurs because
keyup Event
dataTable rendering
You can set up a variable as follows
var isProcessing = false;
YAHOO.util.Event.addListener("reload", "keyup", function(e) {
if(isProcessing) {
return;
}
isProcessing = true;
YAHOO._3657287.dataTable.getDataSource().sendRequest(null, {
success:function(request, response, payload) {
// as shown above
isProcessing = false;
}
});
}
See also here and here
The problem could be related to the line:
myDataTable.resizeHack = function()
{ this.getTbodyEl().parentNode.style.width = "100%"; }
Since you are resizing the width of the table, it is reasonable to assume that the table will need to be re-painted on the screen resulting in the flicker.

Categories

Resources