Closure Function for every class instance (JavaScript) - javascript

I have to JavaScript class called GKChart :-
class GKChart {
constructor(data) {
try {
console.info("Enter: Chart Designing initialize function");
this.chartID = data.id;
this.chartData = data.data;
this.chartCall = new chartCalling();
this.load = this.initialize(this.chartData.config.chartType, this.chartData, this.chartID, this.chartCall);
this.load();
this.resize(this.load);
console.info("Exit: Chart Designing initialize function");
} catch (err) {
console.log("Error Found in GKChart Constructoru", err);
}
}
initialize(chartTypeLoad, chartDataLoad, chartIDLoad, chartCallLoad) {
try {
console.log("Start : initialize");
let chartType = chartTypeLoad;
let chartData = chartDataLoad;
let chartID = chartIDLoad;
var chartCall = chartCallLoad;
/*Define chart css properties*/
var loadIt = function() {
console.warn("Resize Load : "+chartID);
css(document.querySelector("#" + chartID), {
'display': 'block'
});
switch (chartType) {
case "line":
{
chartCall.lineChart(chartData, chartID);
break;
}
case 'bar':
{
chartCall.barChart(chartData, chartID);
break;
}
default:
{
console.log("Invalid choice of chart");
break;
}
}
}
return loadIt;
console.log("End : initialize");
} catch (err) {
console.error("Exception occurred in Home module: " + err.message);
}
}
resize(loadFun) {
try {
window.addEventListener("resize", function (e) {
window.resizeEvt;
window.addEventListener("resize", function () {
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function () {
loadFun();
console.warn("ResizeCalled");
}, 250);
});
});
} catch (err) {
console.log("error occured while resizing the chart");
}
}
}
And i want to call this class for more then 20 instances with some dome data
new GKChart({id: "stepChartComparision", data: stepChartComparision});
new GKChart({id: "stepChartFill", data: stepChartFill});
new GKChart({id: "stepChartComparisionFill", data: stepChartComparisionFill});
...
...
...
So for these all calls i am drawing some canvas charts.
To make these canvas charts responsive i have to draw every chart for resize. So i have tried to create a closure function to keep a copy of "this.load" function, but as i can see its only calling once for the last instance.
Please help me to get it for every instance of call, or in other words i want to resize every singe canvas chart.
Thank you.

My Closure is working properly but due to ASYNC call of setTimeout function, only last call is running, but when i have removed this and tried to run it, its working properly.
Ans Code is :-
resize(loadFun) {
try {
window.addEventListener("resize", function (e) {
window.resizeEvt;
window.addEventListener("resize", function () {
loadFun();
});
});
} catch (err) {
console.log("error occured while resizing the chart");
}
}

Related

Tabulator not working with remote pagination and ajaxURLGenerator

I have an issue with tabulator (4.9.1) and the pagination, when I try to configure it with remote pagination and ajaxUrlGenerator function, it never pass into the generator function, after investigating the code I've noticed that the code of tabulator do the following :
Tabulator.prototype._loadInitialData = function () {
var self = this;
if (self.options.pagination && self.modExists("page")) {
self.modules.page.reset(true, true);
if (self.options.pagination == "local") {
if (self.options.data.length) {
self.rowManager.setData(self.options.data, false, true);
} else {
if ((self.options.ajaxURL || self.options.ajaxURLGenerator) && self.modExists("ajax")) {
self.modules.ajax.loadData(false, true).then(function () {}).catch(function () {
if (self.options.paginationInitialPage) {
self.modules.page.setPage(self.options.paginationInitialPage);
}
});
return;
} else {
self.rowManager.setData(self.options.data, false, true);
}
}
if (self.options.paginationInitialPage) {
self.modules.page.setPage(self.options.paginationInitialPage);
}
} else {
if (self.options.ajaxURL) {
self.modules.page.setPage(self.options.paginationInitialPage).then(function () {}).catch(function () {});
} else {
self.rowManager.setData([], false, true);
}
}
} else {
if (self.options.data.length) {
self.rowManager.setData(self.options.data);
} else {
if ((self.options.ajaxURL || self.options.ajaxURLGenerator) && self.modExists("ajax")) {
self.modules.ajax.loadData(false, true).then(function () {}).catch(function () {});
} else {
self.rowManager.setData(self.options.data, false, true);
}
}
}
};
using the ajaxURLGenerator with the 'local' configuration makes it work correctly in remote.
But then it doesn't do the progressive pagination and doesn't pass the parameters correctly in the ajaxURLGenerator function, probably due to the parsing mecanism that is not called in 'local' mode for the data :
Page.prototype.trigger = function () {
var _this81 = this;
var left;
return new Promise(function (resolve, reject) {
switch (_this81.mode) {
case "local":
left = _this81.table.rowManager.scrollLeft;
_this81.table.rowManager.refreshActiveData("page");
_this81.table.rowManager.scrollHorizontal(left);
_this81.table.options.pageLoaded.call(_this81.table, _this81.getPage());
resolve();
break;
case "remote":
case "progressive_load":
case "progressive_scroll":
_this81.table.modules.ajax.blockActiveRequest();
_this81._getRemotePage().then(function () {
resolve();
}).catch(function () {
reject();
});
break;
default:
console.warn("Pagination Error - no such pagination mode:", _this81.mode);
reject();
}
});
};
At the end it is loading, but all the data when the server return just a json list, but it fail when receiving the object expected for the remote pagination.
Does anyone had the same issue with remote pagination and ajaxURLGenerator? Anyone has an idea how to solve it, without modifying the library?
Thanks in advance

How to use infinite scrolling in meteor

I am working on meteor. I need to implement infinite scrolling on my data inside data list. I don't know how to implement it. I have seen some infinite scrolling packages at atmosphere but i didn't get. As I am new to this technology I didn't understand how to use it.
Template.medicine.events({
'change #Search_Criteria':function (e) {
event.preventDefault();
myvalue=$(e.target).val();
console.log(myvalue);
Meteor.call('searched_medicines',myvalue,function(err,res)
{
if(res)
{
console.log(res);
SessionStore.set("Medicinevalue",res);
}
else {
console.log(err);
}
});
},
'input #search':function (event, template) {
d = $(event.currentTarget).val();
console.log(d);
Meteor.call('fetchValues',myvalue,d,function(error,response)
{
if(response)
{
SessionStore.set("Medi_values",response);
}
else {
console.log(err);
}
});
}
});
Template.medicine.helpers({
// Here will be helper for displaying data in client side//
searched_val:function(){
var a= SessionStore.get("Medicinevalue");
// console.log(a);
return a;
},
myfunction:function(){
var mydata=SessionStore.get("Medi_values");
return mydata;
}
});
Thanks in Advance!!!!!

angular doesn't print data after scanning qr

I'm working with NativeStorage and barcodeScanner plugins for cordova.
The capture works well, and I receive the QRCode, but for any reason angular doesn't print it.
After working a lot on my code, I'm not able to do a valid callback, so angular can print it binding the data.
Here bellow I paste the code.
read.js
(function() {
'use strict';
var read = angular.module('app.read', ['monospaced.qrcode']);
read.controller('ReadController', [
function() {
var data = this;
var qr = function(string) {
data.code = string;
console.log(string);
};
cordova.plugins.barcodeScanner.scan(
function(result) {
if (!result.cancelled) {
if (result.format === "QR_CODE") {
(function(cb) {
cb(result.text);
})(qr);
NativeStorage.getItem("historic", function(d) {
var storage = JSON.parse(d);
storage.push(result.text);
NativeStorage.setItem("historic", JSON.stringify(storage), function(response) {}, function(e) {
console.log(e);
});
}, function(e) {
window.alert("Scanning failed: " + e);
});
}
}
},
function(e) {
window.alert("Scanning failed: " + e);
}, {
"preferFrontCamera": true, // iOS and Android
"showFlipCameraButton": true, // iOS and Android
"prompt": "Place a barcode inside the scan area", // supported on Android only
"formats": "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
"orientation": "portrait" // Android only (portrait|landscape), default unset so it rotates with the device
}
);
}
]);
}());
read.html
<div ng-controller="ReadController as myRead">
<qrcode version="5" error-correction-level="H" size="200" data="{{myRead.code}}" href="{{myRead.code}}"></qrcode>
{{myRead.code}}
</div>
Just adding some extra tests I have done before, I just missed the barcodeScanner.scan process and I did just the storage as I show bellow:
NativeStorage.getItem("historic", function (d) {
var storage = JSON.parse(d);
storage.push('https://google.es');
data.code = 'https://google.es';
NativeStorage.setItem("historic", JSON.stringify(storage), function (response) {}, function (e) {
console.log(e);
});
}, function (e) {
window.alert("Scanning failed: " + e);
});
Could you show me where am I wrong?
Thanks in advice.
A qualified guess is that the callbacks from cordova.plugins.barcodeScanner.scan doesn't trigger AngularJS' digest cycle, which means no dirty checking will be performed, no changes will be detected and the UI won't be updated.
Try wrapping the code in the success callback in $apply:
function(result) {
$scope.$apply(function() {
if (!result.cancelled) {
if (result.format === "QR_CODE") {
(function(cb) {
cb(result.text);
})(qr);
NativeStorage.getItem("historic", function(d) {
var storage = JSON.parse(d);
storage.push(result.text);
NativeStorage.setItem("historic", JSON.stringify(storage), function(response) {}, function(e) {
console.log(e);
});
}, function(e) {
window.alert("Scanning failed: " + e);
});
}
}
});
}

Creating a jQuery container to hold other functions

I am trying to create a simple class or a container to hold few JavaScript methods as shown below.
var Core = (function () {
var Error = {
alert: function() {
alert('Error => alert called');
},
display: function() {
alert('Error => display called');
}
};
var ajax = {
view: function(){
alert('Ajax => view called');
},
update: function(){
alert('Ajax => update called');
}
};
var call = function(){
Error.alert();
Error.display();
ajax.view();
ajax.update();
};
$(document).ready(function(){
call(); // This works fine.
}());
But for some reason I am not able to call these methods outside the container. For instance calling functions as shown below throws error.
$(document).ready(function(){
Core.Error.alert(); // This doesn't work.
Core.Call(); // This doesn't work.
});
Error: Uncaught TypeError: Cannot read property 'Error' of undefined
I can call the functions from within the container. I am new to the concept of jQuery plugins and would appreciate if someone can help me with this.
You can export these methods (read more about Module Pattern), like so
var Core = (function () {
...
return {
Error: Error,
Ajax: ajax,
Call: call
};
})();
Core.Error.alert();
Core.Call();
Example
Change it in:
var Core = {
error: {
alert: function () {
alert('Error => alert called');
},
display: function () {
alert('Error => display called');
}
},
ajax: {
view: function () {
alert('Ajax => view called');
},
update: function () {
alert('Ajax => update called');
}
},
call: function () {
Core.error.alert();
Core.error.display();
Core.ajax.view();
Core.ajax.update();
}
}
$(document).ready(function () {
Core.call(); // This works
}());
Working fiddle

Failed to load routed module requirejs? durandal bug?

I created an Asp.Net MVC and used nuget to add HotTowel (V2.0.1 of 9/11/2013). I created a couple of ViewModel, Models. However, I got the following error.
"Failed to load routed module (viewmodels/myVM). Details: Load timeout for modules: durandal/plugins/router\nhttp://requirejs.org/docs/errors.html#timeout"
Is it the problem of durandal/plugins/router? Or it can be caused by some code I added?
The error occurred at Scripts/durandal/system.js.
var logError = function(error) {
if(error instanceof Error){
throw error;
}
throw new Error(error);
};
The following is the VM code.
define(['services/datacontext', 'durandal/plugins/router', 'services/logger'],
// Remove the durandal/plugins/router and the functions will get rid of the error.
function (datacontext, router, logger) {
var title = 'Event';
var vm = {
activate: activate,
deactivate: deactivate,
refresh: refresh,
events: events,
title: title
};
return vm;
//#region Internal Methods
var events = ko.observableArray();
function activate() {
logger.log(title + ' View Activated', null, title, true);
return datacontext.getEventPartials(events);
}
var deactivate = function () {
events([]);
};
var refresh = function () {
return datacontext.getEventPartials(events, true);
};
//#endregion
});
The following is the call stack
logError [system.js] Line 92 Script
Anonymous function [router.js] Line 359 Script
[External Code]
Anonymous function [system.js] Line 260 Script
[External Code]
[Async Call]
....
Code at router.js,
isProcessing(true);
router.activeInstruction(instruction);
if (canReuseCurrentActivation(instruction)) {
ensureActivation(activator.create(), currentActivation, instruction);
} else {
system.acquire(instruction.config.moduleId).then(function(module) {
var instance = system.resolveObject(module);
ensureActivation(activeItem, instance, instruction);
}).fail(function(err){
system.error('Failed to load routed module (' + instruction.config.moduleId + '). Details: ' + err.message);
});
}
}
And previous one in system.js.
acquire: function() {
var modules,
first = arguments[0],
arrayRequest = false;
if(system.isArray(first)){
modules = first;
arrayRequest = true;
}else{
modules = slice.call(arguments, 0);
}
return this.defer(function(dfd) {
require(modules, function() {
var args = arguments;
setTimeout(function() {
if(args.length > 1 || arrayRequest){
dfd.resolve(slice.call(args, 0));
}else{
dfd.resolve(args[0]);
}
}, 1);
}, function(err){
dfd.reject(err);
});
}).promise();
},
Based on the comments I'd recommend to modify the vm code slightly, so that all variables that are returned via vm are defined before use. In addition 'plugins/router' is used instead of 'durandal/plugins/router'.
define(['services/datacontext', 'plugins/router', 'services/logger'],
// Remove the durandal/plugins/router and the functions will get rid of the error.
function (datacontext, router, logger) {
var title = 'Event';
var events = ko.observableArray();
var deactivate = function () {
events([]);
};
var refresh = function () {
return datacontext.getEventPartials(events, true);
};
var vm = {
activate: activate,
deactivate: deactivate,
refresh: refresh,
events: events,
title: title
};
return vm;
//#region Internal Methods
function activate() {
logger.log(title + ' View Activated', null, title, true);
return datacontext.getEventPartials(events);
}
//#endregion
});
BTW the name Internals methods is misleading as everything in that region is returned via vm. I prefer to work with named function instead, which get created before the return statement if they are returned and place them below the return statement in a Internal methods region if they are not returned.
define(['services/datacontext', 'plugins/router', 'services/logger'],
function( datacontext, router, logger ) {
var title = 'Event';
var events = ko.observableArray();
function deactivate () {
events([]);
}
function refresh () {
return datacontext.getEventPartials(events, true);
}
function activate () {
logger.log(title + ' View Activated', null, title, true);
return datacontext.getEventPartials(events);
}
return {
activate: activate,
deactivate: deactivate,
refresh: refresh,
events: events,
title: title
};
//#region Internal Methods
//#endregion
});

Categories

Resources