Make the local variable to global in extjs - javascript

How to make local variable to global?
Ext.define('A.view.Management', {
extend: 'Ext.container.Container',
requires: [
'A.store.Management',
],
border: false,
chart: null,
hrer: [],
initComponent: function () {
var me = this;
me.jobStore2 = Ext.create('O2a.store.Management');
Ext.Ajax.request({
url: utils.createUrl('api', 'ard-read'),
async: true,
callback: function(opts, success, response) {
try {
if (success) {
var output = App.decodeHttpResp(response.responseText);
const data = output.data;
let myArr = [];
data.map((date) =>
myArr = Object.keys(date).filter(key => key != 'DATE'));
me.hrer =myArr;
console.log(me.hrer);
if (output.success) {
//return output.success;
} else {
//return output.error;
}
} else {
//return 'Unknown Reason';
}
} catch (ex) {
//return ex;
}
}
});
console.log(me.hrer);
I want to take hrer array to outside. When I console.log it outside the ajax request I am getting an empty array which I have defined as globally. I couldn't pass the values which getting inside the ajax request to outside

In ExtJS 4, we used to do:
Ext.define('A.store.SharedData', {
singleton: true,
foo: 'bar',
johnDoeAge: 42,
hrer: []
});
Then require it in whichever component you want to use and consume it like:
Ext.define('A.view.Management', {
extend: 'Ext.container.Container',
requires: [
'A.store.Management',
'A.store.SharedData'
],
initComponent: function () {
var me = this;
A.store.SharedData.hrer = [1, 2, ...];
...
}
...
});

Related

Undefined returned while accessing data of another model of loopback from remote method?

var loopback = require('loopback');
var serviceOffering = loopback.getModelByType('ServiceOffering');
var app = require('../../server/server.js');
module.exports = function (serviceOffering) {
serviceOffering.GetAllOfferings = function (options,category,callback) {
var filter = JSON.parse(JSON.stringify(category));
var arry=[];
var getOrgFil={where:{or:[]}};
var uniqOrList=[];
serviceOffering.find(options,filter, function (err, result) {
for(var i = 0; i < result.length; i++) {
var obj = result[i];
if (arry.indexOf(result[i]._createdBy) === -1) {
arry.push(obj._createdBy);
getOrgFil.where.or.push({UserName:obj._createdBy});
}
}
console.log(getOrgFil);
serviceOffering.app.models.Realm.find(options,getOrgFil, function (err, resl) {
console.log(resl);
return callback(null, resl);
});
});
};
serviceOffering.remoteMethod(
'GetAllOfferings', {
http: { path: '/GetAllOfferings', verb: 'get' },
accepts: { arg: 'category', type: 'object',http: { source: 'query' } },
returns: { type: 'array', root: true }
});
}
I am making a call to 'Realm' model from my 'ServiceOffering' model's remote method to filter and get some data. But the response i am getting for resp is "undefined". I am new to loopback and have very limited idea on how to debug. I was able to print "result", "getOrgFil", but "resp" comes as 'undefined'. Can someone please help me understand why am i getting 'undefined' when i am trying to get the value of resp via the remote method?
I get output as mentioned below
result = [ { SeriviceCategory: 'SCCER',
AssetType: List [ 'ATCOF', 'ATHUS', 'ATMLK' ],
ServiceType: List [ 'STQCR' ],
Identity: null,
_type: 'ServiceOffering',
_createdBy: 'admin',
_modifiedBy: 'admin',
_createdOn: 2018-01-01T09:21:48.638Z,
_modifiedOn: 2018-01-01T09:21:48.638Z,
_scope: List [ 'tenantId:default' ],
_autoScope: { tenantId: 'default' },
_isDeleted: false,
_version: '536c3db2-2323-4004-afb6-2a9e7995aeca',
id: 5a49fdac28a2bd802d8206ba } ]
getOrgFil = { where: { or: [ [Object] ] } }
stringified getOrgFil = {"where":{"or":[{"UserName":"admin"}]}}
resl = undefined
There is no relationship between Realm & ServiceOffering Models.
It will be this
var app = require('../../server/server');
app.models.Realm.find(options,getOrgFil, function (err, resl) { // this instead of serviceOffering.app.models
return callback(null, resl);
});

Access object context from prototype functions JavaScript

I have problems with object scope.
Here is my class code
// Table list module
function DynamicItemList(data, settings, fields) {
if (!(this instanceof DynamicItemList)) {
return new DynamicItemList(data, settings, fields);
}
this.data = data;
this.settings = settings;
this.fields = fields;
this.dataSet = {
"Result": "OK",
"Records": this.data ? JSON.parse(this.data) : []
};
this.items = this.dataSet["Records"];
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
this.dataHiddenInput = $(this.settings["hidden-input"]);
}
DynamicItemList.RESULT_OK = {"Result": "OK"};
DynamicItemList.RESULT_ERROR = {"Result": "Error", "Message": "Error occurred"};
DynamicItemList.prototype = (function () {
var _self = this;
var fetchItemsList = function (postData, jtParams) {
return _self.dataSet;
};
var createItem = function (item) {
item = parseQueryString(item);
item.id = this.generateId();
_self.items.push(item);
return {
"Result": "OK",
"Record": item
}
};
var removeItem = function (postData) {
_self.items = removeFromArrayByPropertyValue(_self.items, "id", postData.id);
_self.dataSet["Records"] = _self.items;
_self.generateId = makeIdCounter(findMaxInArray(_self.dataSet["Records"], "id") + 1);
return DynamicItemList.RESULT_OK;
};
return {
setupTable: function () {
$(_self.settings["table-container"]).jtable({
title: _self.settings['title'],
actions: {
listAction: fetchItemsList,
deleteAction: removeItem
},
fields: _self.fields
});
},
load: function () {
$(_self.settings['table-container']).jtable('load');
},
submit: function () {
_self.dataHiddenInput.val(JSON.stringify(_self.dataSet["Records"]));
}
};
})();
I have problems with accessing object fields.
I tried to use self to maintain calling scope. But because it is initialized firstly from global scope, I get Window object saved in _self.
Without _self just with this it also doesn't work . Because as I can guess my functions fetchItemsList are called from the jTable context and than this points to Window object, so I get error undefined.
I have tried different ways, but none of them work.
Please suggest how can I solve this problem.
Thx.
UPDATE
Here is version with all method being exposed as public.
// Table list module
function DynamicItemList(data, settings, fields) {
if (!(this instanceof DynamicItemList)) {
return new DynamicItemList(data, settings, fields);
}
this.data = data;
this.settings = settings;
this.fields = fields;
this.dataSet = {
"Result": "OK",
"Records": this.data ? JSON.parse(this.data) : []
};
this.items = this.dataSet["Records"];
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
this.dataHiddenInput = $(this.settings["hidden-input"]);
}
DynamicItemList.RESULT_OK = {"Result": "OK"};
DynamicItemList.RESULT_ERROR = {"Result": "Error", "Message": "Error occurred"};
DynamicItemList.prototype.fetchItemsList = function (postData, jtParams) {
return this.dataSet;
};
DynamicItemList.prototype.createItem = function (item) {
item = parseQueryString(item);
item.id = this.generateId();
this.items.push(item);
return {
"Result": "OK",
"Record": item
}
};
DynamicItemList.prototype.setupTable = function () {
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: this,
fields: this.fields
});
};
DynamicItemList.prototype.load = function () {
$(this.settings['table-container']).jtable('load');
};
DynamicItemList.prototype.submit = function () {
this.dataHiddenInput.val(JSON.stringify(this.dataSet["Records"]));
};
DynamicItemList.prototype.removeItem = function (postData) {
this.items = removeFromArrayByPropertyValue(this.items, "id", postData.id);
this.dataSet["Records"] = this.items;
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
return DynamicItemList.RESULT_OK;
};
DynamicItemList.prototype.updateItem = function (postData) {
postData = parseQueryString(postData);
var indexObjToUpdate = findIndexOfObjByPropertyValue(this.items, "id", postData.id);
if (indexObjToUpdate >= 0) {
this.items[indexObjToUpdate] = postData;
return DynamicItemList.RESULT_OK;
}
else {
return DynamicItemList.RESULT_ERROR;
}
};
Your assigning a function directly to the prototype. DynamicItemList.prototype= Normally it's the form DynamicItemList.prototype.somefunc=
Thanks everyone for help, I've just figured out where is the problem.
As for last version with methods exposed as public.
Problematic part is
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: {
listAction: this.fetchItemsList,
createAction: this.createItem,
updateAction: this.updateItem,
deleteAction: this.removeItem
},
fields: this.fields
});
};
Here new object is created which has no idea about variable of object where it is being created.
I've I changed my code to the following as you can see above.
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: this,
fields: this.fields
});
And now it works like a charm. If this method has drawbacks, please let me know.
My problem was initially in this part and keeping methods private doesn't make any sense because my object is used by another library.
Thx everyone.
You need to make your prototype methods use the this keyword (so that they dyynamically receive the instance they were called upon), but you need to bind the instance in the callbacks that you pass into jtable.
DynamicItemList.prototype.setupTable = function () {
var self = this;
function fetchItemsList(postData, jtParams) {
return self.dataSet;
}
function createItem(item) {
item = parseQueryString(item);
item.id = self.generateId();
self.items.push(item);
return {
"Result": "OK",
"Record": item
};
}
… // other callbacks
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: {
listAction: fetchItemsList,
createAction: createItem,
updateAction: updateItem,
deleteAction: removeItem
},
fields: this.fields
});
};

Elastic Search JS Function Return value

Question :
Why is the variable (resultVisitor) returning undefined?
When i log hits inside the function searchVisitors(), the log is returning an array of objects?
Any Ideas?
/* Get passanten telling */
var searchVisitorParams = {
index: 'veenendaal',
type: 'passanten',
size: 100,
body: {
fields: ["Tijdsperiode", "201_WE_Veenendaal", "940_HEMA_Veenendaal"],
query: {
"match_all": {}
},
sort: {
Tijdsperiode: "asc"
}
}
};
function searchVisitors() {
client.search(searchVisitorParams).then(function (body) {
var hits = body.hits.hits;
console.log(hits)
return hits;
});
}
var resultVisitor = searchVisitors();
console.log(resultVisitor)
Return is inside a callback function. I would do something like this:
/* Get passanten telling */
var searchVisitorParams = {
index: 'veenendaal',
type: 'passanten',
size: 100,
body: {
fields: ["Tijdsperiode", "201_WE_Veenendaal", "940_HEMA_Veenendaal"],
query: {
"match_all": {}
},
sort: {
Tijdsperiode: "asc"
}
}
};
function searchVisitors(callback) {
client.search(searchVisitorParams).then(function (body) {
var hits = body.hits.hits;
callback(hits);
});
}
searchVisitors(function(hits){ // Results are inside hits variable
console.log(hits);
// .... Your code ... //
});

unable to access function from another function using this within same object

I have the following:
$scope.option = {
generateID:function(){
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
},
values : [
{id:this.generateId()},
{id:this.generateId()},
{id:this.generateId()},
{id:this.generateId()}
],
markCorrect : function(option){
},
remove:function(option)
{
this.values = this.values.filter(function(value){return value.id!=option.id})
}
}
I always get a this.generateId is not a function error. I am pretty sure that i am missing something fundamental here!
It may be better to store the id generator function in a separate function so it is easier to reference:
function generateId = function() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
}
$scope.option = {
generateID: generateId,
values : [
{id: generateId()},
{id: generateId()},
{id: generateId()},
{id: generateId()}
],
markCorrect : function(option){
},
remove:function(option)
{
this.values = this.values.filter(function(value){return value.id!=option.id})
}
}
The primary issue is that you're trying to access properties of $scope.option in the middle of declaring it. Try doing something like this instead:
$scope.option = (function () {
function generateId () {
/* logic */
}
return {
values: [
{id: generateId()}
// ...
],
markCorrect: function () {},
remove: function () {}
};
}) ();
This is the 'revealing module pattern', i.e. a function that returns an object forming a closure on some other data or functionality.
There is a typo; rename generateID to generateId.

Passing a local variable into an event handler

h.d.d.w = Ext.extend(w.g.a,
{
initComponent: function () {
exampleFunctionA('Monday');
//other fields omitted
}
exampleFunctionA: function (dayOfWeek) {
this['WeekdayHoursStore' +dayOfWeek] = new Ext.data.Store({
proxy: a.b.c.getProxy('d/e.asmx/f'),
reader: g.h.i.j(
[
//array of config objects removed
]),
sortInfo: //omitted
});
this['WeekdayHoursStore' +dayOfWeek].load(
{
params:
{
//parameters removed
}
});
this['WeekdayHoursStore' +dayOfWeek].on("load", this._renderHours, this);
//irrelevant code removed
},
_renderHours: function (dayOfWeek) {
var dayIndex;
for(var i = 0; i<7; i++){
if(this.weekdays[i] === dayOfWeek){
dayIndex = i;
break;
}
}
var record = this.WeekdayHoursStore.getAt(dayIndex);
this['UseDefaultValue' +dayIndex] = record.get("UseDefault");
}
//further class members omitted
}
How can I pass dayOfWeek into _renderHours?
You can create an anonymous function and call this._renderHours from it:
this['WeekdayHoursStore' +dayOfWeek].on("load", function() {
this._renderHours(dayOfWeek);
}, this);

Categories

Resources