I have a function that return something like [object object] no my value that I wanted , I do almost every thing to get the value but no hope.
When I try to show that object using toSource() I got something like that.
({state:(function (){return state;}), always:(function (){deferred.done(arguments).fail(arguments);return this;}), then:(function (){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var action=tuple[0],fn=fns[i];deferred[tuple[1]](jQuery.isFunction(fn)?function(){var returned=fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify);}else{newDefer[action+"With"](this===deferred?newDefer:this,[returned]);}}:newDefer[action]);});fns=null;}).promise();}), promise:(function (obj){return obj!=null?jQuery.extend(obj,promise):promise;}), pipe:(function (){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var action=tuple[0],fn=fns[i];deferred[tuple[1]](jQuery.isFunction(fn)?function(){var returned=fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify);}else{newDefer[action+"With"](this===deferred?newDefer:this,[returned]);}}:newDefer[action]);});fns=null;}).promise();}), done:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;}), fail:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;}), progress:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;})})
Could any one explain me? And I know my function is Asynchronous.
How could solve this problem ?
Here is my code:
module.Order = Backbone.Model.extend({
initialize: function (attributes) {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.pos = attributes.pos;
this.sequence_number = this.pos.pos_session.sequence_number++;
debugger;
var odoo = []
var call = this
this.uid = this.generateUniqueId();
this.pro = this.get_the_other_main().done(
function (result) {
}).always(function (result) {
odoo.push(result)
call.set({
creationDate: new Date(),
orderLines: new module.OrderlineCollection(),
paymentLines: new module.PaymentlineCollection(),
name: _t("Order ") + this.uid,
client: null,
sales_person: null,
sales_person_name: null,
new_id: odoo[0]
})});
alert(odoo[0])//// Must be adddddedd
this.selected_orderline = undefined;
this.selected_paymentline = undefined;
this.screen_data = {}; // see ScreenSelector
this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
this.temporary = attributes.temporary || false;
return this;
},
get_the_other_main: function () {
var dfd = new jQuery.Deferred();
new instance.web.Model("pos.order").call('get_the_product', []).done(
function (results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
}).always(function(results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
}).always(function(results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
});
alert('')////If i remove that it will return undefind for this.pos
return dfd
You seem to have problem of asynchronous call.
(see the comments below)
// you call get_the_other_main which return a Promise !
this.get_the_other_main().then(
function (result) {
// when the Promise resolve you set this.pro,
// what is this here ?? are you sure of the beahviour ?
// |
// V
this.pro=result//got it right <---------------------- +
// |
// |
});// |
// You set this.pro to another Promise, at this moment the previous this.pro is not set !
this.pro=this.get_the_other_main().then(
function (result) {
this.pro=result //got it right <----------------------------------------+
}); // |
// when you call alert, this.pro is a Promise not resolved !at this moment the previous this.pro is not set !
alert(this.pro.toSource()) //[object object]
// logicaly it show the code source of your deffered / Promise !
to solve your issue try like that :
module.Order = Backbone.Model.extend({
initialize: function(attributes) {
var curOrder = this;
Backbone.Model.prototype.initialize.apply(this, arguments);
this.pos = attributes.pos;
this.sequence_number = this.pos.pos_session.sequence_number++;
debugger; // ??????
this.uid = this.generateUniqueId();
var odoo = []
this.get_the_other_main().then(
function(result) {
curOrder.pro = result; //got it right
curOrder.set({
creationDate : new Date(),
orderLines : new module.OrderlineCollection(),
paymentLines : new module.PaymentlineCollection(),
name : _t("Order ") + curOrder.uid,
client : null,
sales_person : null,
sales_person_name: null,
new_id : curOrder.pro
});
curOrder.selected_orderline = undefined;
curOrder.selected_paymentline = undefined;
curOrder.screen_data = {}; // see ScreenSelector
curOrder.receipt_type = 'receipt'; // 'receipt' || 'invoice'
curOrder.temporary = attributes.temporary || false;
curOrder.trigger('orderready' , curOrder);
});
return this;
// be careful because the process above is not done again, when you return this, it will be resolved later
},
get_the_other_main: function() {
var dfd = new jQuery.Deferred();
new instance.web.Model("pos.order").call('get_the_product', []).done(
function(results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
});
return dfd
},
Related
I have the above error on this method:
function addContentType(listItem){
var promise = getContentTypeOfCurrentItem(listItem.ID.toString());
promise.then(function(cname){
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
});
return promise;
}
Entire code is here:
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(function(listItems) {
var listItemsWithValues = [];
if(listItems) {
var enumerator = listItems.getEnumerator();
var promises = [];
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function(propertyName) {
var value = listItem.get_item(propertyName);
if(propertyName === "PwC_JobCodesMulti"){
jobvalue = "";
value.forEach(function(jobvalues){
jobvalue+= jobvalues.get_lookupValue() +";";
})
listItemValues[propertyName] = jobvalue;
}else{
listItemValues[propertyName] = value;
}
});
listItemsWithValues.push(listItemValues);
}
var promises = listItemsWithValues.map(addContentType);
Promise.all(promises).then(youCanUseTheData);
function youCanUseTheData(){
/*
At this point, each listItem holds the 'Document Type' info
*/
listItemsWithValues.forEach(function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
//listItem["FileRef"] = dispFormUrl;
//listItem["Bill Cycle"] = dispFormUrl;
var parentLink = listItem["FileRef"];
arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
});
}
}
var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
deferred.resolve(listItemsWithValues);
})
.catch (function (message) {
deferred.reject();
});
return deferred.promise;
}
function addContentType(listItem){
var promise = getContentTypeOfCurrentItem(listItem.ID.toString());
promise.then(function(cname){
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
});
return promise;
}
function getContentTypeOfCurrentItem(id) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
listItem = oList.getItemById(id);
clientContext.load(listItem);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved getContentTypeOfCurrentItemt");
var ctid = listItem.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
return Promise.resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
deferred.reject(errorInfo);
}
);
}
Not sure exactly what I am missing
Update 1:
I changed the code as Niels replied tere, but then I get the error below:
Uncaught Error: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
If I analyze the changes done, the only thing that changed on the method is the return new promise, the rest is the same and it was working before. I didnt make all changes as Niels did, just need to make this work without too much effort. :)
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(function(listItems) {
var listItemsWithValues = [];
if(listItems) {
var enumerator = listItems.getEnumerator();
var promises = [];
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function(propertyName) {
var value = listItem.get_item(propertyName);
if(propertyName === "PwC_JobCodesMulti"){
jobvalue = "";
value.forEach(function(jobvalues){
jobvalue+= jobvalues.get_lookupValue() +";";
})
listItemValues[propertyName] = jobvalue;
}else{
listItemValues[propertyName] = value;
}
});
listItemsWithValues.push(listItemValues);
}
var promises = listItemsWithValues.map(addContentType);
Promise.all(promises).then(youCanUseTheData);
function youCanUseTheData(){
/*
At this point, each listItem holds the 'Document Type' info
*/
listItemsWithValues.forEach(function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
//listItem["FileRef"] = dispFormUrl;
//listItem["Bill Cycle"] = dispFormUrl;
var parentLink = listItem["FileRef"];
arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
});
}
}
var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
deferred.resolve(listItemsWithValues);
})
.catch (function (message) {
deferred.reject();
});
return deferred.promise;
}
function addContentType(listItem){
return getContentTypeOfCurrentItem(listItem.ID.toString()).then(function(cname){
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
});
}
function getContentTypeOfCurrentItem(id) {
return new Promise(function (resolve, reject) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
listItem = oList.getItemById(id);
clientContext.load(listItem);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved getContentTypeOfCurrentItemt");
var ctid = listItem.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
reject(errorInfo);
}
);
});
}
getContentTypeOfCurrentItem should return a Promise. Assuming that clientContext.executeQueryAsync does not return a promise, since it is using handlers:
function getContentTypeOfCurrentItem(id) {
return new Promise(function (resolve, reject) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill
Cycles");
listItem = oList.getItemById(id);
clientContext.load(listItem);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved
getContentTypeOfCurrentItemt");
var ctid = listItem.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
reject(errorInfo);
}
);
});
}
addContentType can be more easy as well:
function addContentType(listItem){
return getContentTypeOfCurrentItem(listItem.ID.toString()).then(function(cname) {
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
}).catch(function(error) {
$log.warn("Server error");
});
}
The getContentTypeOfCurrentItem function doesn't return anything. Just modify it to return your promise (assuming of course that clientContext.executeQueryAsync returns a promise):
function getContentTypeOfCurrentItem(id) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
listItem = oList.getItemById(id);
clientContext.load(listItem);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
return clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved getContentTypeOfCurrentItemt");
var ctid = listItem.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
return Promise.resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
deferred.reject(errorInfo);
}
);
}
I defined a JavaScript function using a custom service and I called this function using the service in my controller. This function uses two parameters: The first one is input which I am getting by hitting the below API and the second one is the value of the year which I'm getting using ng-model directive. When I am calling this function in my controller I am getting an error like type is not defined or id is not defined etc. Is it the right way to call a JavaScript function in the controller. Please suggest me.
$http.get("http://152.144.218.70:8080/USACrime/api/crimeMultiple?city=" +$scope.strCity + "&crime=" + $scope.type1 + "&model=" + model).success(function (result) {
$scope.prograssing = false;
console.log("manisha", $scope.strCity);
console.log("kanika", result);
$scope.output = result;
console.log("monga", $scope.output);
$scope.hex = hexafy.year_city($scope.output,$scope.type);
console.log("service", $scope.hex);
});
myapp.js
var app= angular.module("myApp",["ngRoute","leaflet-directive","pb.ds.components"]);
var geomarker = new L.FeatureGroup();
app.service('hexafy', function() {
this.year_city = function (input2,years) {
if(years.toLowerCase()=="all"){
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] =outerBoundary;
themes = [];
for(var i in input){
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for(var j in input[i]["prediction"]){
dict = {};
if(yrs.indexOf(input[i]["prediction"][j]["year"])>-1){
dict["name"] = input[i]["prediction"][j]["year"]+" "+input[i]["crime"]+" Crime";
dict["description"] = input[i]["crime"]+" Crime for "+input[i]["prediction"][j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase()+"CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]',crimeThemeValue["individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes",JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
};
});
});
1) .success and .error methods are deprecated and it is not good to go with it. Instead you'd better use .then(successCallback, errorCallback)
2) To use a service method the proper way is to it like this:
app.service('myService', function() {
var service = {
method:method
};
return service;
function method() {
//Logic
}
})
So in your case the way to go is:
app.service('hexafy', function () {
return {
years_city: function (input2, years) {
if (years.toLowerCase() == "all") {
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] = outerBoundary;
themes = [];
for (var i in input) {
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for (var j in input[i]["prediction"]) {
dict = {};
if (yrs.indexOf(input[i]["prediction"][j]["year"]) > -1) {
dict["name"] = input[i]["prediction"][j]["year"] + " " + input[i]["crime"] +
" Crime";
dict["description"] = input[i]["crime"] + " Crime for " + input[i]["prediction"]
[j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase() + "CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]', crimeThemeValue[
"individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes", JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
}
}
})
Below is my code. if we use set timeout function we got all data but we not use we are not getting inspection data which is coming from my local db. i want use deferred and promises in my code. Thanks in advance.
function onclickToCall() {
this.$('.check-list > .check-list-box').each(function (i) {
var j = i + 1;
var answer_req = $(this).attr("data-isReq");
var checklist_guid = $(this).attr("data-guid");
var question_type = $(this).attr("data-type");
var yes_no = $("input:radio[name='radio_" + j + "']:checked").val();
var notes = $(this).find('#txtAreaNotes_' + j).val();
var attachment_url = $(this).find(".txtCameraImage").attr("data-path");
var appConfig = DriverConnectApp.State.get('config_settings');
var item = {};
item.checklist_guid = checklist_guid;
item.yes_no = yes_no;
item.attachment_url = attachment_url;
item.notes = notes;
if (question_type == 2) { // For Vehical visual inspection
var dataPromise = that.getInspectionData(checklist_guid);
dataPromise.done(function (response, vh_image) {
var inspectionItem = {};
inspectionItem.vh_url = vh_image;
inspectionItem.details = response;
item.vh_inspection = inspectionItem;
that.detailsArr.push(item);
});
} else {
item.vh_inspection = {};
that.detailsArr.push(item);
}
});
// after finish and push all data we need to call function here
test();
}
getInspectionData: function (checklist_guid) {
var that = this;
var deferred = $.Deferred();
that.dbchecklist.getVehicleInspectionlist(checklist_guid, function (data, res) {
var details = [];
if (data.length) {
var img = data[0].vh_image;
var arr = JSON.parse(data[0].vh_details);
for (var k = 0; k < arr.length; k++) {
var items = {};
items.number = arr[k].number;
items.notes = arr[k].notes;
items.attachment_url = arr[k].attachment_url;
details.push(items);
}
deferred.resolve(details, img);
} else {
deferred.resolve(details, img);
}
});
return deferred.promise();
}
i was tested to the IdentyfyTask.
But I could not get a response before the value addCallback.
i want to the pnu values.
But pnu vaule was alwayes undefined...
my code is follows.
function poiClick(){
agmap.addEvent("click", function(evt){
getPoi= krcgis.Function.PoiClick(agmap ,evt);
console.log("X === ",getPoi.x);
console.log("Y === ",getPoi.y);
console.log("PNU === ",getPoi.pnu);
});
}
PoiClick : function(map, evt) {
poiInfo = {};
poiInfo.x =evt.mapPoint.x;
poiInfo.y =evt.mapPoint.y;
var targetLayerId = 'LP_PA_CBND';
var url = map.Layers.getLayerInfo(targetLayerId).SVC_URL;
var map = map.getMap();
//파라미터 설정.
var idParams = new krcgis.core.tasks.IdentifyParameters();
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.returnGeometry = true;
idParams.tolerance = 0;
idParams.layerOption = krcgis.core.tasks.IdentifyParameters.LAYER_OPTION_ALL;
idParams.width = map.width;
idParams.height = map.height;
idTask = new krcgis.core.tasks.IdentyfyTask(url);
idTask
.execute(idParams)
.addCallback(function (response) {
if (response) {
poiInfo.pnu =response[0].value;
}
});
return poiInfo;
}
The results were as follows.
IdentifyTask returns a IdentifyResult object. so you code response[0].value will be undefined.
you should use something like response[0].feature.attributes.PNU
I am using the method of a javascript object to create HTML to write that object.
Within that method I have a date (in string format as a SQL Date) which I format to dd MMM YYYY in an external method. The external method works fine returning the string I need, but when I set the variable within my object's method it is returned as undefined.
Hereby the relevant code:
function CreateReview(reviewID, visitDate) {
var reviewObject = {
iD: reviewID,
visitDate: visitDate,
CreateReviewObject : function(c) {
var reviewContainer = document.createElement('div');
reviewContainer.id = 'Review_' + this.iD;
reviewContainer.className = 'Card Review';
var headerDIV = document.createElement('div');
headerDIV.className = 'Header';
var dateTagsDIV = document.createElement('div');
dateTagsDIV.className = 'DateTags';
var datesDIV = document.createElement('div');
datesDIV.className = 'Dates';
var formattedVisitDate = getFormattedDate(this.visitDate);
console.log(formattedVisitDate);
var dateDIV = document.createElement('div');
dateDIV.className = 'Date';
dateDIV.innerHTML = formattedVisitDate;
datesDIV.appendChild(dateDIV);
dateTagsDIV.appendChild(datesDIV);
headerDIV.appendChild(dateTagsDIV);
reviewContainer.appendChild(headerDIV);
return reviewContainer;
}
};
return reviewObject;
}
function getFormattedDate(input) {
input = input.replace(/-/g,'/');
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
p2 = parseInt(p2);
p3 = parseInt(p3);
var months = ['jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'];
var date = (p3<10?"0"+p3:p3) + " " + months[parseInt(p2-1)] + " " + p1;
console.log(date);
return date;
});
}
The output of the console in getFormattedDate is then
12 mei 2015
While in CreateReview it is
undefined
I have tried the following way as well:
function CreateReview(reviewID, restaurant, kitchenTypes, tags, pictures, ratings, thumbPicture, visitDate, introduction, description) {
var reviewObject = {
iD: reviewID,
visitDate: visitDate,
CreateReviewObject : function(c) {
var getFormattedVisitDate = function(visitDate) {
return function() { getFormattedDate(visitDate); };
};
var reviewContainer = document.createElement('div');
reviewContainer.id = 'Review_' + this.iD;
reviewContainer.className = 'Card Review';
var headerDIV = document.createElement('div');
headerDIV.className = 'Header';
var dateTagsDIV = document.createElement('div');
dateTagsDIV.className = 'DateTags';
var datesDIV = document.createElement('div');
datesDIV.className = 'Dates';
var formattedVisitDate = getFormattedVisitDate(this.visitDate);
console.log(formattedVisitDate);
var dateDIV = document.createElement('div');
dateDIV.className = 'Date';
dateDIV.innerHTML = formattedVisitDate;
datesDIV.appendChild(dateDIV);
dateTagsDIV.appendChild(datesDIV);
headerDIV.appendChild(dateTagsDIV);
reviewContainer.appendChild(headerDIV);
return reviewContainer;
}
};
return reviewObject;
}
function getFormattedDate(input) {
input = input.replace(/-/g,'/');
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
p2 = parseInt(p2);
p3 = parseInt(p3);
var months = ['jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'];
var date = (p3<10?"0"+p3:p3) + " " + months[parseInt(p2-1)] + " " + p1;
console.log(date);
return date;
});
}
Which gives me this output in in CreateReview:
return function() { getFormattedDate(visitDate); };
Why does the CreateReview call return undefined when the console does not?
In your function getFormattedDate(), you have
var result = input.replace(pattern, function(match,p1,p2,p3) {... return date; });
so result contains the returned value of the replace function, but getFormattedDate doesn't return anything ==> undefined when called from CreateReview.
Add return result; at the end of the function getFormattedDate.