on commenting one function code works, otherwise it fails - javascript

In my application when I am trying to copy one object its getting copied but if I am defining another function call, the code which was executing properly gives error, don't know why. Any help on this is highly appreciated, and thanks in advance
If I comment this function that._createCustomStore(data); everything works good, if I uncomment this it gives me error as Uncaught ReferenceError: _newParent is not defined on this line copiedParent = _newParent;
below is my code
_genericInnerCopy: function(_childObj) {
copiedParent = {};
that = this;
model = that.model;
var record = Ext.create(model, {
Name: _childObj.get('Name'),
//Parent: _newParent.get("_ref");,
});
record.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
console.log("Done");
//that._copyChild();
} else {
console.log("error");
}
}
})
that._all_pis.push(record);
copiedParent = _newParent;
var store = Ext.create('Rally.data.custom.Store', {
data: that._all_pis,
listeners: {
load: function(store,data,success) {
that._updateAll(store, data, copiedParent);
},
scope: that
},
});
//console.log("record values", that._all_pis);
},
_updateAll: function(store,data, copiedParent) {
that = this;
Rally.data.BulkRecordUpdater.updateRecords({
records: data,
propertiesToUpdate: {
Parent: copiedParent.get("_ref")
},
success: function(readOnlyRecords){
//all updates finished, except for given read only records
},
scope: that
});
that._createCustomStore(data);
},
_createCustomStore: function(data) {
me = this;
Ext.create('Rally.data.custom.Store', {
data: data,
//model: 'PortfolioItem/' + _newParent.get('PortfolioItemTypeName'),
autoSync:true,
listeners: {
load: function(store,data,success) {
console.log("store value", store);
console.log("data value", data);
console.log("success value", success);
},
scope: me
},
});
},
onqModelRetrieved: function() {
var that = this;
that._type = 'PortfolioItem/' + that._type,
Rally.data.ModelFactory.getModel({
type: that._type,
success: this.onModelRetrieved,
scope: this
});
},
onModelRetrieved: function(model) {
this.model = model;
this.createFeature();
},
createFeature: function() {
var record = Ext.create(this.model, {
Name: "(Copy of) " + this._newObj.get('Name'),
});
record.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
_newParent = result
Ext.Msg.alert('created ' + result.get('PortfolioItemTypeName') + ':', result.get('Name'));
}
else{
console.log("error");
}
}
});
}
});

Try define it and use it like this:
_newParent: null,
_genericInnerCopy: function(_childObj) {
copiedParent = {};
that = this;
model = that.model;
var record = Ext.create(model, {
Name: _childObj.get('Name')
//Parent: _newParent.get("_ref");,
});
record.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
console.log("Done");
//that._copyChild();
} else {
console.log("error");
}
}
})
that._all_pis.push(record);
copiedParent = that._newParent;
var store = Ext.create('Rally.data.custom.Store', {
data: that._all_pis,
listeners: {
load: function(store,data,success) {
that._updateAll(store, data, copiedParent);
},
scope: that
}
});
//console.log("record values", that._all_pis);
},
_updateAll: function(store,data, copiedParent) {
that = this;
Rally.data.BulkRecordUpdater.updateRecords({
records: data,
propertiesToUpdate: {
Parent: copiedParent.get("_ref")
},
success: function(readOnlyRecords){
//all updates finished, except for given read only records
},
scope: that
});
that._createCustomStore(data);
},
_createCustomStore: function(data) {
me = this;
Ext.create('Rally.data.custom.Store', {
data: data,
//model: 'PortfolioItem/' + _newParent.get('PortfolioItemTypeName'),
autoSync:true,
listeners: {
load: function(store,data,success) {
console.log("store value", store);
console.log("data value", data);
console.log("success value", success);
},
scope: me
}
});
},
onqModelRetrieved: function() {
var that = this;
that._type = 'PortfolioItem/' + that._type,
Rally.data.ModelFactory.getModel({
type: that._type,
success: this.onModelRetrieved,
scope: this
});
},
onModelRetrieved: function(model) {
this.model = model;
this.createFeature();
},
createFeature: function () {
var that = this;
var record = Ext.create(this.model, {
Name: "(Copy of) " + this._newObj.get('Name')
});
record.save({
callback: function (result, operation) {
if (operation.wasSuccessful()) {
that._newParent = result
Ext.Msg.alert('created ' + result.get('PortfolioItemTypeName') + ':', result.get('Name'));
}
else {
console.log("error");
}
}
});
}

Related

When I edited directly in the grid instead of the modal at the right the filter never drops but when I edit in modal and save the filter dropped

class ProductInfoDetailsViewModel {
constructor(parent, productInfoWindowId, inventoryId, productId, supplierId, store) {
this._parent = parent;
this._created = false;
this._productInfoWindowId = productInfoWindowId;
this._inventoryId = inventoryId;
this._productId = productId;
this._supplierId = supplierId;
this._store = store;
}
_getMvvmData(inventoryId, productId, supplierId) {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/ProductRowInfoSite/GetInventoryControl',
data: {
'inventoryId': inventoryId,
'productId': productId,
'supplierId': supplierId,
},
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
resolve(result);
},
error: function (jqXHR, textStatus, errorThrown) {
reject([jqXHR, textStatus, errorThrown]);
},
type: 'POST',
});
});
}
async create() {
let self = this;
let userStore = new UserStore();
//productInfoTextGrid
this._productInfoDetailsViewModel = kendo.observable({
value: {},
close: function () {
//$("#generalProductInfoWindow").data("kendoWindow").close();
//closeWindow();
},
not: function (value) {
return !this.get(value);
},
save: function (e) {
let productInfoTextGrid = $(self._productInfoWindowId + ' ' + '#productInfoTextGrid').data('kendoGrid');
/* productInfoTextGrid.saveChanges();*/
let orderUnitsGrid = $(self._productInfoWindowId + ' ' + '#orderUnitsGrid').data('kendoGrid');
let selectedRefHistProd = null;
try {
selectedRefHistProd = this.get('value.SelectedRefHistProd').ProductId;
} catch (error) {
// may be set to null and that's fine/TK.
}
var data = {
ProductId: self._productId,
InventoryId: self._inventoryId,
SupplierId: self._supplierId,
Fmean: this.get('value.Fmean'),
FMAD: this.get('value.FMAD'),
FTrend: this.get('value.FTrend'),
SelectedSeason: this.get('value.SelectedSeason').SeasonId,
MinQuantity: this.get('value.MinQuantity'),
SelectedOrderUnitNo: this.get('value.SelectedOrderUnit').UnitNo,
LeadTime: this.get('value.LeadTime'),
LeadTimeDeviation: this.get('value.LeadTimeDeviation'),
StockKeepInterest: this.get('value.StockKeepInterest'),
MaxLevel: this.get('value.MaxLevel'),
MinLevel: this.get('value.MinLevel'),
OrderQuantity: this.get('value.OrderQuantity'),
ReorderLevel: this.get('value.ReorderLevel'),
EnableManualSetRAndQ: this.get('value.EnableManualSetRAndQ'),
ForecastError: this.get('value.ForecastError'),
SelectedHistoryProductId: selectedRefHistProd,
};
var dataString = JSON.stringify(data);
$.ajax({
url: '/ProductRowInfoSite/SaveParameters',
data: {
data: dataString,
},
dataType: 'json',
// "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
//options.success(result);
self._store.dispatch({ type: ActionProductInfoWindow.Saving });
self._parent.refreshParentGrids();
},
error: function (result) {
displayAjaxError(result);
},
type: 'POST',
});
let userStore = new UserStore();
let finishSaved = userStore.translatedString('SOLOSupplier.ProductInfoWindows.FinishSaved');
displaySuccess(finishSaved);
productInfoTextGrid.saveChanges();
orderUnitsGrid.saveChanges();
},
recalc: function () {
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
var a = validator.validate();
},
products: new kendo.data.DataSource({
type: 'json',
serverFiltering: true,
pageSize: 100,
transport: {
read: function (options) {
$.ajax({
url: '/ProductRowInfoSite/GetProductInventoryList',
data:
{
'inventoryId': self._inventoryId,
'productId': self._productId,
'data': options.data,
},
//"filter": filter
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
options.success(result.HistProducts);
},
error: function (result) {
// notify the data source that the request failed
options.error(result);
},
type: 'POST',
});
},
parameterMap: function (data, type) {
return kendo.stringify($.extend({ 'text': $(data.filter.filters).get(0).value }, data));
},
},
}),
isEnabled: true,
onValidate: function (e) {
console.log('onValidate');
let maxLevel = this.get('value.MaxLevel');
let minLevel = this.get('value.MinLevel');
let userStore = new UserStore();
let validationErrorMessage = userStore.translatedString('uctrlSupplierWeb.MaxLevelMinLevelWarning');
let validator = $(self._productInfoWindowId).kendoValidator({
messages: {
custom: validationErrorMessage,
},
rules: {
custom: function (input) {
if (input.is('[name=minLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=minLevelParameter]') && input.val() !== '' && maxLevel !== null) {
return maxLevel > minLevel;
}
if (input.is('[name=maxLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=maxLevelParameter]') && input.val() !== '' && minLevel !== null) {
return maxLevel > minLevel;
} else {
return true;
}
},
},
},
).data('kendoValidator');
if (validator.validate() === true) {
self._store.dispatch({ type: ActionProductInfoWindow.Changing });
} else {
self._store.dispatch({ type: ActionProductInfoWindow.Cancelling });
}
},
});
kendo.bind($(self._productInfoWindowId + ' ' + '#tabInventoryControl'), self._productInfoDetailsViewModel);
try {
let result = await self._getMvvmData(self._inventoryId, self._productId, self._supplierId);
self._productInfoDetailsViewModel.products.read();
self._productInfoDetailsViewModel.set('value', result);
if (result.UnitsOnOrderAfterLeadtime === true) {
if ($(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox')) {
let widget = $(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox');
widget.wrapper.find('input').addClass('lightRed');
}
}
if ($(self._productInfoWindowId + ' ' + '#minLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#minLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
if ($(self._productInfoWindowId + ' ' + '#maxLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#maxLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
validator.validate();
let element = $(self._productInfoWindowId);
window.kendo.ui.progress(element, false);
} catch ([jqXHR, textStatus, errorThrown]) {
displayAjaxError(jqXHR, textStatus, errorThrown);
productInfoDetailsViewModel.set('value', []);
window.kendo.ui.progress(element, false);
}
}
}
Saving edits in product info modal deletes used filters on products grid
if (productNo === null) {
let newFilter = await self._getFilterOnlyFromLocalStorage();
let totalFilter = $(self._gridId).data("kendoGrid").dataSource.filter();
totalFilter.filters.push.apply(totalFilter.filters, newFilter.filters);
$(self._gridId).data("kendoGrid").dataSource.filter(newFilter);
self._setPredefinedFilterButton(self);
}
}

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

How can i fix my module pattern to work

I have a module in a different file which should essentially carry out my ajax requests for me (this is in ajaxCall.js), I am trying to add this module to the global window object so that i can use it in another file called (basket-page.js), but I get an error stating
Uncaught TypeError: Cannot read property 'process' of undefined(…)
AjaxCall.js
"user strict";
window.ajaxCall = window.ajaxCall || {}
var ajaxCall = (function () {
var api = {
process: function (destinationUrl, dataToPost, callbackFunction) {
$.ajax({
url: destinationUrl,
data: dataToPost,
method: "POST",
dataType: "JSON",
success: function (data) {
if (element.length > 0) {
callbackFunction(data, element);
}
},
error: function (req, status, errorObj) {
console.log(status);
}
});
}
}
window.ajaxCall = api;
return api;
})();
basket-page.js
"use strict";
basket = basket || {};
var basket = (function (ajax) {
var api = {
init: function () {
$("#tblBasket").dataTable({
bFilter: false,
pageLength: 10,
paging: true,
autoWidth: true,
columns:
[
{ "orderDataType": "dom-text", type: "string" },
{ "orderDataType": "dom-text-numeric" },
null
],
fixedColumns: true
});
},
removeBasketProductRow: function (data, element) {
if (data === true) {
element.remove();
}
}
};
$("#btnRemoveBasketProduct").click(function() {
var product = $(this).closest("tr");
var productId = product.attr("id");
window.ajaxCall.process("/Products/RemoveBasketProduct", productId, api.removeBasketProductRow);
});
return api;
})(window);
$(document).ready(function () {
basket.init();
});
Remove all the function wrapping. It's unnecessary.
"user strict";
window.ajaxCall = {
process: function (destinationUrl, dataToPost, callbackFunction) {
$.ajax({
url: destinationUrl,
data: dataToPost,
method: "POST",
dataType: "JSON",
success: function (data) {
if (element.length > 0) {
callbackFunction(data, element);
}
},
error: function (req, status, errorObj) {
console.log(status);
}
});
}
}
The issue was making sure i had my other script file loaded already, since this is what adds object to the global window object.

scope of javascript variable in the class

inside click_save() method of Controller, this is not pointing to the controller instance, but instead it points to button instance
How to get access to this. so it points to controller and I can do this.userModelDialog().method call
```
// --- Controller manages/dispatches tasks of view and model
function Controller() {
var controller = this;
api = new API();
var table = $('#table');
this.userModelDialog = new UserModalDialog();
$('button[data-type="edituser"]').on("click", function(e) {
controller.click_button(this);
});
// Register the button handlers
$.each(["save", "close", "copy", "delete", "reset"], function(index, id) {
msg.clear();
$("#" + id).click(controller["click_" + id]);
});
}
$.extend(Controller.prototype, {
click_user: function(id) {
api.getUser(id)
.done(function(data) {
_.keys(data).forEach(function(property) {
$('#' + property).val(data[property]);
});
})
.fail(function(data) {
alert('fail');
});
$('#userDetails').modal('show');
},
click_button: function(button) {
var id = $(button).attr('data-id');
this.click_user(id);
},
click_save: function(button) {
this.userModelDialog.submit();
msg.show({
TYPE: 'success',
MESSAGE: 'saved successfull!'
});
$('#userDetails').modal('hide');
},
click_new: function() {
},
click_copy: function() {
},
click_delete: function() {
},
click_reset: function() {
},
click_row: function(row) {
var id = $(row).attr('data-uniqueid');
this.click_user(id);
},
updateFromServer: function(data, callback) {
msg.show(data);
callback(data);
}
});
```
// Register the button handlers
$.each(["save", "close", "copy", "delete", "reset"], function(index, id) {
msg.clear();
var methodName = 'click_' + id;
if (controller[methodName]) {
$("#" + id).click(controller[methodName].bind(controller));
} else {
console.log('There is not method in class with name: ' + methodName);
}
});

How to execute string as a function using AngularJS?

I have these two functions defined:
function fetchYPosts() {
$http.get("/postsY/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
};
function fetchXPosts() {
$http.get("/postsX/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
};
I am passed an id and a string ('X' or 'Y' is what I want the end-user to pass to me) from the front-end. I have this code which handles when the string is passed:
self.handler = function(id, XOrY) {
$http.post("/" + XOrY + "/" + id + "/handle/")
.then(function(response) {
functionToCall = "fetch" + XOrY + "Posts()";
# Here is where I want to call funcitonToCall.
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};
With that said, given a variable which holds a string, how do I call the function which has the name of the string variable?
You should select the correct method using something like this:
var fetcher = XOrY == 'x' ? fetchXPosts : fetchYPosts;
which can be used like:
self.handler = function(id, XOrY) {
var fetcher = XOrY == 'x' ? fetchXPosts : fetchYPosts;
$http.post("/" + XOrY + "/" + id + "/handle/")
.then(function(response) {
fetcher();
# Here is where I want to call funcitonToCall.
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};
If you have a situation where there's just too many different fetching functions, you can instead define them like this as part of a hash:
var fetch = {
YPosts: function() {
$http.get("/postsY/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
},
XPosts: function() {
$http.get("/postsX/")
.then(function(response) {
self.posts = response.data;
}, function(response) {
self.posts = {};
});
}
}
and grab the function from fetch[XorY]:
self.handler = function(id, XOrY) {
$http.post("/" + XOrY + "/" + id + "/handle/")
.then(function(response) {
fetch[XorY]();
# Here is where I want to call funcitonToCall.
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};
you can encapsule these two function in an object, and call this service in your method like this
var service = {
fetchXPosts: function(){},
fetchYPosts: function(){}
}
self.handler = function(id, XORY) {
service['fetch'+XORY+'posts']();
}

Categories

Resources