Setting variable through external method in method of object - javascript

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.

Related

Correct Way To Re-Use HTML Blocks and Insert Dynamic Content With Javascript

I have a server that collects data from 10 sources and constantly pushes JSON data to a webpage. The page uses JSON.Parse to get it into an object widgetData. The object widgetData has 10 properties that I want to display in the "widget".
So, the server is pushing WidgetData1, WidgetData2, etc..
For each widgetData, I want to create/instantiate a new widget and show the data. If widget1 exists, then update the widget. Also, the widgets should be sorted by some text property(e.g. widgetdata.name).
Here's what I've done so far, but the it doesn't seem that robust:
<script type="text/javascript">
var properties = ["MachineID", "p1","p2,"p3","p4"];
var currentWidget;
function CreateBlock(widgetData)
{
var widgetID = widgetData.MachineID.replace(/ /g,"_");
var myWidget = document.getElementById('widget-' + widgetID);
if (myWidget == null)
{
CreateCard(widgetID);
}
var currentDate = new Date();
var day = currentDate.getDay();
var month = currentDate.getMonth(); //Be careful! January is 0 not 1
var year = currentDate.getFullYear();
var hour = currentDate.getHours();
var min = currentDate.getMinutes();
var sec = currentDate.getSeconds();
var dateString = year + "-" + ZeroPad(month+1,2) + "-" + day + " " + ZeroPad(hour,2) + ":" + ZeroPad(min,2) + ":" + ZeroPad(sec,2);
var data;
for (let i = 0; i < properties.length; i++)
{
data = widgetData[properties[i]];
AddDataElement(widgetID,properties[i],data);
}
AddDataElement(widgetID,"Timestamp",dateString);
}
//create the card
function CreateCard(cardID)
{
var parent
var newdiv
var cardElement = document.createElement("div");
cardElement.className = "card";
cardElement.id = "widget-" + cardID;
cardElement.style = "height:500px;";
parent=cardElement;
newdiv = document.createElement("div");
newdiv.className = "card-header";
parent.appendChild(newdiv);
//parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-body";
newdiv.id = "cardbody";
parent.appendChild(newdiv);
parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-title";
newdiv.id = "title";
newdiv.textContent = "title";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
newdiv.className = "card-sub-title";
newdiv.id = "subtitle";
newdiv.textContent = "subtitle";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
parent.appendChild(newdiv);
//last add to the parent div
var parent = document.getElementById("Cards");
parent.appendChild(cardElement);
}
//Add a data element
function AddDataElement(machineID, title, value)
{
var cardElement = document.getElementById("widget-" + machineID);
var cardElementBody = findChild("widget-" + machineID, "cardbody");
var dataElement = findChild2(cardElementBody, title);
if (dataElement == null)
{
dataElement = document.createElement("div");
dataElement.id = title;
dataElement.className = "card-item";
}
dataElement.innerText = title + ": " + value;
cardElementBody.appendChild(dataElement);
}
function CreateElement(parentDivObject, childName)
{
var dataElement = document.createElement('DIV');
dataElement.id = childName;
dataElement.textContent = childName;
parentDivObject.appendChild(dataElement);
}
function findChild(idOfElement, idOfChild)
{
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
function findChild2(parentElement, idOfChild)
{
//let element = document.getElementById(idOfElement);
return parentElement.querySelector('[id=' + idOfChild + ']');
}
function ZeroPad(num, places)
{
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
</script>
<script type="text/javascript">
var widgetList = new Set(); //hold list of widgets
var start = function () {
var inc = document.getElementById('incomming');
var wsImpl = window.WebSocket || window.MozWebSocket;
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');
inc.innerHTML += "connecting to server ..<br/>";
// create a new websocket and connect
window.ws = new wsImpl('ws://localhost:8181/');
//when data is comming from the server, this method is called
//ws.onmessage = function (evt) {
// inc.innerHTML += evt.data + '<br/>';
//};
ws.onmessage = function (evt)
{
var machineStatus = JSON.parse(evt.data);
if (!widgetList.has(machineStatus.MachineID))
{
widgetList.add(machineStatus.MachineID)
}
CreateBlock(machineStatus)
}
// when the connection is established, this method is called
ws.onopen = function () {
inc.innerHTML += '.. connection open<br/>';
};
// when the connection is closed, this method is called
ws.onclose = function () {
inc.innerHTML += '.. connection closed<br/>';
}
form.addEventListener('submit', function(e){
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
</script>
What is an alternative, proper way, or best practice to accomplish this?

Can i call multiple java script functions with in controller?

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;
}
}
})

how make objects counter via prototype?

I wrote a script, which creates 3 objects. The constructor has a local variable mushroomsCount:
Mushroom = function(num) {
var mushroomsCount = 0;
this.id = num;
this.Create();
}
Mushroom.prototype.Create = function() {
this.mushroomsCount++;
}
Mushroom.prototype.Display = function() {
console.log('mushromms count total is: ' + Mushroom.mushroomsCount);
}
$(document).ready(function() {
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display(); // first way
Mushroom.Display(); // second way
});
after creating the objects, I try to display the number of the objects at Mushroom.prototype.Display(), but I'm getting undefined.
codepen
You can use a property on Mushroom itselft (like you already had, but not had accessed).
function Mushroom(num) {
this.id = num;
this.create();
}
Mushroom.mushroomCount = 0; // this is public!
Mushroom.prototype.create = function () {
Mushroom.mushroomCount++;
}
Mushroom.prototype.display = function () {
document.write('mushromms count total is: ' + Mushroom.mushroomCount + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Or use a closure with an IIFE:
var Mushroom = function () {
var mushroomCount = 0;
var f = function (num) {
this.id = num;
this.create();
};
f.prototype.create = function () { mushroomCount++; }
f.prototype.display = function () { document.write('mushromms count total is: ' + mushroomCount + '<br>'); }
return f;
}();
var mushroom = [new Mushroom(0), new Mushroom(1), new Mushroom(2)];
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Simple count instances of Mushroom 'class':
function Mushroom(num) {
this.id = num;
Mushroom.count++;
}
Mushroom.count = 0;
Mushroom.prototype.Display = function () {
document.write('mushromms count total is: ' + Mushroom.count + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display();

The [object object] can't be determined and shown in console

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
},

Why does this give an Uncaught TypeError

var hatIds = [113333065] //This is the Ids
var PriceWanting = 15 //This is the price
var Loop = setInterval(function(){
for (var Id in hatIds) {
var hatLink = "http://m.roblox.com/items/" + hatIds[Id] + "/privatesales"
$.get(hatLink,function(data){
var Regex = /\<span class="currency-robux">([\d,]+)\<\/span\>/
var PriceSelling = data.match(Regex)[1]
PriceSelling = Number(PriceSelling.replace(",",""))
if (PriceSelling <= PriceWanting) {
var Regex2 = /<a href="\/Catalog\/VerifyTransfer\DuserAssetOptionId=([\d,]+)\Damp;expectedPrice=([\d,]+)">/
var HatBuyId = data.match(Regex2)[1]
var HatBuyLink = "http://m.roblox.com/Catalog/VerifyTransfer?userAssetOptionId=" + HatBuyId + "&expectedPrice=" + PriceSelling
var Explorer = document.createElement('iframe');
function Buy(){
Explorer.contentDocument.forms[0].submit();
};
Explorer.onload = Buy;
Explorer.width = "300";
Explorer.height = "400";
Explorer.src = HatBuyLink;
document.body.innerHTML = "";
document.body.appendChild(Explorer);
clearInterval(Loop)
}
});
}
console.log("!")
},0)
For some reason, I seem to be getting an Uncaught TypeError. I don't know why and would like some help in fixing it.

Categories