Closure inside loop - not sure how to address - javascript

for (var i = 0; i < stops.length; i++) {
var code = stops[i].atcocode;
var name = stops[i].common;
var direction = stops[i].direction;
var alertMessage = "View departures for " + stops[i].common + (directionText !== 'Unknown' ? (" (facing " + directionText + ")") : "") + "?";
this.map.addMarker({
icon: icon,
position: new plugin.google.maps.LatLng(stops[i].latitude, stops[i].longitude)
}, function(markerCallback) {
markerCallback.code = code;
markerCallback.name = name;
markerCallback.direction = direction;
markerCallback.alert = alertMessage;
markerCallback.addEventListener(plugin.google.maps.event.MARKER_CLICK, function(clickedMarker) {
alert(markerCallback.name);
});
_this.busStopMarkers.push(markerCallback);
});
}
JavaScript closure inside loops – simple practical example
I have viewed the question above and am not sure how to apply the same answer logic into my scenario. Could somebody please show me an example as to how I can make the alert show the indexed item in the array rather than the last one?

Create a callback factory:
function createCallback(_this, code, name, direction, alertMessage) {
return function(markerCallback) {
markerCallback.code = code;
markerCallback.name = name;
markerCallback.direction = direction;
markerCallback.alert = alertMessage;
markerCallback.addEventListener(plugin.google.maps.event.MARKER_CLICK, function(clickedMarker) {
alert(markerCallback.name);
});
_this.busStopMarkers.push(markerCallback);
};
}
Then use it to create a function inside your loop:
for (var i = 0; i < stops.length; i++) {
var code = stops[i].atcocode;
var name = stops[i].common;
var direction = stops[i].direction;
var alertMessage = "View departures for " + stops[i].common + (directionText !== 'Unknown' ? (" (facing " + directionText + ")") : "") + "?";
var callback = createCallback(_this, code, name, direction, alertMessage);
this.map.addMarker({
icon: icon,
position: new plugin.google.maps.LatLng(stops[i].latitude, stops[i].longitude)
}, callback);
}

You can create an anonymous function like this:
for (var i = 0; i < stops.length; i++) {
(function(me, stop){ // Use the stop as an argument, this function is directly called
var code = stop.atcocode;
var name = stop.common;
var direction = stop.direction;
var alertMessage = "View departures for " + stop.common + (directionText !== 'Unknown' ? (" (facing " + directionText + ")") : "") + "?";
me.map.addMarker({
icon: icon,
position: new plugin.google.maps.LatLng(stop.latitude, stop.longitude)
}, function(markerCallback) {
markerCallback.code = code;
markerCallback.name = name;
markerCallback.direction = direction;
markerCallback.alert = alertMessage;
markerCallback.addEventListener(plugin.google.maps.event.MARKER_CLICK, function(clickedMarker) {
alert(markerCallback.name);
});
_this.busStopMarkers.push(markerCallback);
});
})(this, stops[i]); // Pass the stop
}

Related

Brainlabs adwords script remove firstpagemaxbid restriction

Can some body help me modify this script.
The purpose of the script is to change bids for the keywords based on average position. One of the assumptions that the script has is that it sets a firstpagebid for the keyword but it won't allow for the bid to go below the firstpagebid even if the position is too high.
Is there a way to remove this restriction? so basically if the new cpc calculated is lower than the first page bid then it allows for the new cpc to be lower than the firstpage bid.
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.5
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Updated 2016-08-30 to correct label reading from reports
* Updated 2016-09-14 to update keywords in batches
* Updated 2016-10-26 to avoid DriveApp bug
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 14.50;
// Bids will not be increased past this maximum.
var minBid = 3.0;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 10.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = true;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.20;
var bidDecreaseProportion = 0.25;
var targetPositionTolerance = 0.3;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"\n");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
Logger.log("File '" + dataFile + "' has been read.");
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the current date/time
var currentTime = new Date(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "MMM dd,yyyy HH:mm:ss"));
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var hourOfDay = currentTime.getHours();
var dayOfWeek = days[currentTime.getDay()]; //Added on 9/21/2015
// Prevent adjustments if not in between 8am and 11pm and Diffrent running time by date - Added on 9/21/2015 (important allows to set time based on day)
switch (dayOfWeek) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
if (hourOfDay < 8 || hourOfDay >= 21) {
Logger.log("Not the Right Time");
return;
}
break;
case 'Saturday':
case 'Sunday':
if (hourOfDay < 8 || hourOfDay >= 18) {
Logger.log("Not the Right Time");
return;
}
break;
}
Logger.log("Right Time");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
Logger.log(labelIds.length + " position labels have been found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
if (row["Labels"].trim() == "--") {
continue;
}
var labels = JSON.parse(row["Labels"].toLowerCase()); // Labels are returned as a JSON formatted string
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
Logger.log(uniqueIds.length + " labelled keywords found");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/* var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Batch the keyword IDs, as the iterator can't take them all at once
var idBatches = [];
var batchSize = 5000;
for (var i=0; i<uniqueIds.length; i += batchSize) {
idBatches.push(uniqueIds.slice(i,i+batchSize));
}
Logger.log("Updating keywords");
// Update each batch
for (var i=0; i<idBatches.length; i++) {
try {
updateKeywords(idBatches[i]);
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords(idBatches[i]);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Logger.log("Writing file.");
// var content = resultsString();
// file.setContent(content);
Logger.log("Finished.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords(idBatch) {
var keywordIterator = AdWordsApp.keywords()
.withIds(idBatch.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
As I understand, the script increases the cpcBid when the current average position is too high, and decreases it when the position is too low.
But when the bid is decreased and the previous bid is more than firstPageBid, the new bid will not decrease below firstPageBid.
Remove
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
to allow your new bid to go lower than firstPageBid.

Proper approach for complex / nested JavaScript-object creation within another object

The following code is meant to be a short example for a simple construct of a reusable object. This is a very simple, one level depth object, put as many props and methods as you like and just assign them.
function someDesiredReusableType(optionally, pass, ctor, pars, here) {
//core obj to return
var DesiredTypeCrtor = {
propSkiingLocation: "canada",
OrderTickets: function(optionally){
var tryRoomWView = optionaly;
print(
"Dear " + ctor +", your request for " +
propSkiingLocation + " is now being processed: an " +
tryRoomWView + " request was notified, we understand you have " + pars + " for cross country transportation, confirmation email will be sent " + here + " as soon as we process your order. }
}
};
return DesiredTypeCrtor
}
Here is an example of this use:
var DesrVacSkC = someDesiredReusableType("could really help!",null, "mr. Bean", "my mini", "Fun#bbc.co.uk")
//oh..almost forgot
DesrVacSkC.OrderTickets();
As this imaginative object, is actually not as simple as I did use in my code, it does work as is (didn't try this actual one, as it's just an example.)
But this next setup that is similarly using the same approach is buggy somewhat.
This is an example for an object I have successfully and in a blink of an eye implemented as a nested object using the exact same approach as the buggy object, which I do not understand why they Applied the not with same approach by the browser.
//this is an important one, a smart property / value holder I came up with and does work perfectly, as a nested member.
function Rprp(parVal) {
var cretdprp = {
propVal: parVal,
propValAsint: parseInt(parVal)
};
return cretdprp;
}
But the next one, here below, does not, as it lacks the proper approach for the initialization of ownedFefCollCore
Uncaught TypeError: Cannot read property 'HElmTColl' of undefined
//this is an important one, that was started as a very good one, with adding it to the object below, up until I have added ownedFefCollCore member.
function CreateFileEditForm_Manager() {
//as i do usually base/inner/creator and a return obj
var Repo = {
CsDataLocals:
{
GetCurLastfileId:Rprp($("#HLocModelData_LastFileId").val())
},
FormFldNames:
{ JRdrData_FileName: "JRdrData_FileName" },
//this is my bugg ! with and without new keyword & as function or Object!!
ownedFefCollCore: new FefCollCore(),
//and this is the line that chrome get's is anger on --> all day long
FeFDivWFldsColl: this.ownedFefCollCore.HElmTColl,
FeFDivWFlds_IdColl: this.ownedFefCollCore.HElmT_IdColl,
FeFDivWFldsCollAdd: function (parId, parFefDivWrpDivflds) {
this.ownedFefCollCore.CollAdd(parId, parFefDivWrpDivflds);
},
/ ........
//some more code was removed trying to keep it as short as possible
}
//fefa stands for fileRecord Edit Form , core just says nothing, is there to imply the 'thing' is to be shared between variation of instances from the base object
I found the following approach in my research for less error prone constructs, but even this one does not correct the bug. And it was found among some others, such as this Object.create()
var FefCore = JClassProto({
initialize: function () {
this.HElmTColl = new Array();//was originally [] ...
//i changed because i wanted to eliminate any doubt that it's one of the reasons my code is ... Somewhere undefined , now i know (pretty sure they might be little different but both are ok.) it's not it.
this.HElmT_IdColl = new Array();
this.CollAdd = function (parId, parHElmT) {
this.HElmTColl.push(parHElmT);
this.HElmT_IdColl.push(parId);
}
this.Coll_Remove = function (parHElmT) {
this.HElmTColl.pop(parHElmT);
}
// this is the first move, if a new object(which is an element in the array) about to be created,
// call this to make sure not exist for i create do
this.ElmObjCanCreate = function (parId) {
return this.getIndexOfValuInDivWFldsColl(parId) < 0;
}
this.HElmTColl_FindById = function (parId) {
var collindexofCurFileReadyDivWrpFlds = this.getIndexOfValuInDivWFldsColl(parId);
return this.HElmTColl[collindexofCurFileReadyDivWrpFlds];
}
this.getIndexOfValuInHElmTColl = function (parId) {
return $.inArray(parId, this.HElmT_IdColl);
}
}
});
And last but not least, my original code (right after the attempt to create it as a base /shared object).
function FefCollCore() {
this.Cr = {
HElmTColl: new Array(),
HElmT_IdColl: new Array(),
CollAdd: function (parId, parHElmT) {
this.HElmTColl.push(parHElmT);
this.HElmT_IdColl.push(parId);
},
Coll_Remove: function (parHElmT) {
this.HElmTColl.pop(parHElmT);
},
CollNeedCreate: function (parId) {
return this.getIndexOfValuInDivWFldsColl(parId) < 0;
},
HElmTColl_FindById: function (parId) {
var collindexofCurFileReadyDivWrpFlds = this.getIndexOfValuInDivWFldsColl(parId);
return this.HElmTColl[collindexofCurFileReadyDivWrpFlds];
},
getIndexOfValuInHElmTColl: function (parId) {
return $.inArray(parId, this.HElmT_IdColl);
}
};
return this.Cr;
}
//and this is the line that chrome get's is anger on --> all day long
FeFDivWFldsColl: this.ownedFefCollCore.HElmTColl,
If interpret Question correctly, you could try to set FeFDivWFldsColl as a function that returns this.ownedFefCollCore.HElmTColl
var FefCore = function() {
this.e = new Array();
this.e.push(2);
}
function CreateFileEditForm_Manager() {
var Repo = {
a: 0,
b: 1,
c: new FefCore(),
// set `FeFDivWFldsColl` value as a function
d: function() {
// `this.c` : `new FefCore()` , `this.c.e` : `new Array()`
return this.c.e
}
};
return Repo
}
var Fef = new CreateFileEditForm_Manager();
console.log(Fef.d())
var cont = "...see console";
var DivEmptyhtml = document.createElement('div');
var elmst = document.createElement('style');
function stringcss (){
return ".cssEmptyhtml{ \r\n\tmargin:auto; margin-top:10px; margin-bottom:20px;"+
" text-align:center; top:10px;"+
" width:40%; padding: 5px; height: 100px; " +
"background-color:rgb(96,116,243); "+
"color: #B5fee8; "+
"background-image:" +
" linear-gradient(to right bottom, #2983bC 24%, #284a4b 77%);"+
" box-shadow: 8px 10px 50px 20px rgb(55, 55, 55); "+
" -webkit-border-radius:10px;border-radius:10px; }";
}
//elmst.innerHTML = stringcss();
DivEmptyhtml.innerHTML = cont;
DivEmptyhtml.className = "cssEmptyhtml";
DivEmptyhtml.attributes["id"] ="DivEmptyhtml";
$("head").append(elmst);
$("body").append(DivEmptyhtml);
$(elmst).attr("id","elmst");
//$(".cssEmptyhtml").attr("style",stringcss());
$(elmst).text(stringcss());
var strS, strF, message;
var indx = 123;
var count = 135;
indx = ++count - 1;
var init = true;
//now me
var programSteps = 0;
var starting = "starting";
console.log(starting);
function Log(strLine) {
var d = new Date,
DS = d.getSeconds(),
Dms = d.getMilliseconds().toString();
console.log("[step#" + (++programSteps) + "] " + DS + "." + Dms.substring(0, 2) + "> " + strLine);
}
//...see console
function LogObj(p_type) {
function Fnl_t_t() {
this.obj = "\r\n\t\t";
}
function Fnl_5xt() {
this.obj = "\r\n\t\t\t\t";
}
var obj = {
doNewLineBold: function(boolPrint, value, value2, value3, value4) {
var nlttcopy = this.backnl_t_t.obj;
this._nl_t_t = lnobj1.backnl_5xt.obj+ "|========> [ " + value;
this._nl_t_t += value2 != "" ? " " + value2 : "";
this._nl_t_t += value3 != "" ? " " + value3 : "";
this._nl_t_t += value4 != "" ? " " + value4 : "";
this._nl_t_t += " ] <=============|" + nlttcopy;
if (boolPrint) {
Log(this._nl_t_t);
return "";
} else return this._nl_t_t;
},
doLineBold: function(boolPrint, value, value2, value3, value4) {
var nlttcopy = this.backnl_t_t.obj;
this._nl_t_t = "|========> [ " + value;
this._nl_t_t += value2 != "" ? " " + value2 : "";
this._nl_t_t += value3 != "" ? " " + value3 : "";
this._nl_t_t += value4 != "" ? " " + value4 : "";
this._nl_t_t += " ] <=============|" + nlttcopy;
if (boolPrint) {
Log(this._nl_t_t);
return "";
} else return this._nl_t_t;
},
_type: {
val: p_type,
formated: ""
},
doformatedHeader: function() {
var splts = this._type.val.split(' ');
for (var i = 0; i < splts.length; i++) {
this._type.formated += splts[i] + this.ErowR;
}
return "|========> [ " + this._type.formated +
" ] <=============|" + this.backnl_5xt.obj;
},
doformatedTail: function() {
return this.backnl_5xt.obj + "|========> [ END_ " + this._type.formated + "_END] <=============|" + this.backnl_t_t.obj;
},
_nl_t_t: function() {
return "\r\n\t\t";
},
backnl_5xt: new Fnl_5xt(),
backnl_t_t: new Fnl_t_t(),
ErowR: ">",
nlArowR : new Fnl_5xt().obj + ">"
};
return obj;
}
var lnobj1 = LogObj("listWcounter1() arr"); //create object #1
var lnobj2 = LogObj("listWcounter2() arr"); //make sure #2 is not a-copy
var header1 = lnobj1.doformatedHeader();
var Tail1 = lnobj1.doformatedTail();
var header2 = lnobj2.doformatedHeader();
var Tail2 = lnobj2.doformatedTail();
var nlarowR1 = lnobj1.backnl_5xt.obj + lnobj1.ErowR;
var nlarowR2 = lnobj2.backnl_t_t.obj + lnobj2.ErowR;
Log(header1 + lnobj1.ErowR + " starting1... " + nlarowR1 + " is init1 ok?, and index1 is Ok? " + indx + Tail1);
Log(header2 + lnobj2.ErowR + " starting2... " + nlarowR1 + " is init2 ok?, and index2 is Ok? " + indx + Tail2);
var newbold = lnobj1.doLineBold(0, "a", "b", "c", "d") + lnobj1.backnl_5xt.obj;
Log("newbold looks Like: " + newbold);
lnobj1.doLineBold(1, "A", "B", "C", "D");
lnobj1.doNewLineBold(1, "e", "f", "g", "h");
Log(lnobj1.nlArowR);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

adding to existing array on click just empties the array why?

Another angularJS question i have scope binding a click that should add one value on the first click ad another value on the second click but it just keeps returning and empty array and filling the first value again why? :
scope.dbclickalert = function (scope, $watch) {
var getCheckInDate = this.cellData.date;
var formatcheckindate = new Date(getCheckInDate);
var checkingdates = [];
var curr_datecell = formatcheckindate.getDate();
var padded_day = (curr_datecell < 10) ? '0' + curr_datecell : curr_datecell;
var curr_monthcell = formatcheckindate.getMonth() + 1;
var padded_month = (curr_monthcell < 10) ? '0' + curr_monthcell : curr_monthcell;
var curr_yearcell = formatcheckindate.getFullYear();
var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
var checkindatestrg = "checkindate";
console.log(checkingdates.length);
if (checkingdates.length < 2) {
alert("element exists in array");
checkingdates.push('checkoutdate');
checkingdates.push(date_stringcell);
console.log(checkingdates + checkingdates.length);
} else {
checkingdates.push('checkindate');
checkingdates.push(date_stringcell);
}
var setCheckInDate = el.hasClass('checkInDate');
if (checkingdates === true) {
alert('You have allready set your check In Date');
} else {
el.addClass('checkInDate');
$('#checkoutbar').addClass('datePickerchecout');
}
$(".date-cell").each(function removeclasses() {
$(this).removeClass('true');
});
return getCheckInDate;
};
ok so when i declare this outside of the function i get undefined error:
scope.checkingdates = [];
scope.dbclickalert = function(scope, $watch){
var getCheckInDate = this.cellData.date;
var formatcheckindate = new Date(getCheckInDate);
var checkingdates = scope.checkingdates;
var curr_datecell = formatcheckindate.getDate();
var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
var curr_monthcell = formatcheckindate.getMonth() + 1;
var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
var curr_yearcell = formatcheckindate.getFullYear();
var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
var checkindatestrg = "checkindate";
console.log(checkingdates.length);
if (checkingdates.length < 2){
alert("element exists in array");
checkingdates.push('checkoutdate');
checkingdates.push(date_stringcell);
console.log(checkingdates+checkingdates.length);
}else{
checkingdates.push('checkindate');
checkingdates.push(date_stringcell);
}
var setCheckInDate = el.hasClass('checkInDate');
if (checkingdates === true){
alert('You have allready set your check In Date');
} else{
el.addClass('checkInDate');
$('#checkoutbar').addClass('datePickerchecout');
}
$(".date-cell").each(function removeclasses() {
$(this).removeClass('true');
});
return getCheckInDate;
};
ok in the third version of this it the same data "the date" again if the same div has been clicked but not if a second div with the same ng-click="dbclickalert()" is clicked why?
link: function(scope, el, attributes, dateSheetCtrl, $watch) {
scope.checkingdatesarry = [];
scope.dbclickalert = function(){
var getCheckInDate = this.cellData.date;
var formatcheckindate = new Date(getCheckInDate);
var checkingdates = scope.checkingdates;
var curr_datecell = formatcheckindate.getDate();
var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
var curr_monthcell = formatcheckindate.getMonth() + 1;
var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
var curr_yearcell = formatcheckindate.getFullYear();
var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
var checkindatestrg = "checkindate";
var checkoutdatestrg = "checkoutdate";
if( $.inArray('checkindate', scope.checkingdates) !== -1 ) {
scope.checkingdatesarry.push(checkoutdatestrg);
scope.checkingdatesarry.push(date_stringcell);
console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);
}
else{
scope.checkingdatesarry.push(checkindatestrg);
scope.checkingdatesarry.push(date_stringcell);
console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);
}
var setCheckInDate = el.hasClass('checkInDate');
if (scope.checkingdates === true){
alert('You have allready set your check In Date');
} else{
el.addClass('checkInDate');
$('#checkoutbar').addClass('datePickerchecout');
}
$(".date-cell").each(function removeclasses() {
$(this).removeClass('true');
});
return scope.checkingdatesarry;
};
ok for anyone that cares the answer was that because my div's where being created with a angularJS directive it was returning and array per div instead of one global array I have taken the array all the way out of the directive and moved it into a service and it works fine.
Because you redefined the array with empty list in the dbclickalert action. So every time when the action is triggered, the array will be empty.
var checkingdates = [];
You should move it outside the function and declare as
$scope.checkingdates = []; //In your code, you may use scope.checkingdates = []; if you renamed the $scope when you inject it

Javascript error after upgrade to Drupal 7

I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.

Trouble hiding/showing divs in using DOM/js/css

I am trying to make a debugger that will be dynamiaclly created with some variables. The names on the left div need to show a div for the corresponding variables Description,Variable ID, and initial Value as well as another div that will show history and lock status when variables are updated later. Where I am having trouble is properly adding the show/hide to the dom I think. Everything starts hidden and then when I click a name the Variables for that name show up but the next click doesn't hide the values from the former. Also any cleanup/optimization advice?
<script type="text/javascript">
var variableIDArray = {};
function loadVariables(variables) {
if (typeof variables != "object") { alert(variables); return; }
var namearea = document.getElementById('namearea');
var description = document.getElementById('description');
var varid = document.getElementById('varid');
var initialvalue = document.getElementById('initialvalue');
var valuelock = document.getElementById('valuelock');
for (var i = 0; i < variables.length - 1; i++) {
var nameDiv = document.createElement('div');
nameDiv.id = variables[i].variableID + "namearea";
nameDiv.className = "nameDiv";
nameDiv.onclick = (function (varid) {
return function () { showvariable(varid); };
})(variables[i].variableID);
nameDiv.appendChild(document.createTextNode(variables[i].name));
namearea.appendChild(nameDiv);
var descriptionDiv = document.createElement('div');
descriptionDiv.id = variables[i].variableID + "description";
descriptionDiv.className = "descriptionDiv";
descriptionDiv.appendChild(document.createTextNode("Description : " + variables[i].description));
description.appendChild(descriptionDiv);
var varidDiv = document.createElement('div');
varidDiv.id = variables[i].variableID + "varid";
varidDiv.className = "varidDiv";
varidDiv.appendChild(document.createTextNode("Var ID : " + variables[i].variableID));
varid.appendChild(varidDiv);
var initialvalueDiv = document.createElement('div'); ;
initialvalueDiv.id = variables[i].variableID + "initialvalue";
initialvalueDiv.className = "initialvalueDiv";
initialvalueDiv.appendChild(document.createTextNode("Initial Value : " + variables[i].value));
initialvalue.appendChild(initialvalueDiv);
var valuelockDiv = document.createElement('div');
valuelockDiv.id = variables[i].variableID + "valuelock";
valuelockDiv.className = "valuelockDiv ";
valuelockDiv.appendChild(document.createTextNode("Value : " + variables[i].value));
valuelockDiv.appendChild(document.createTextNode("Lock : " + variables[i].locked.toString()));
valuelock.appendChild(valuelockDiv);
variableIDArray[variables[i].variableID];
}
};
function showvariable(varid) {
for (v in variableIDArray)
hide(variableIDArray[v]);
show(varid + "description");
show(varid + "varid");
show(varid + "initialvalue");
show(varid + "valuelock");
}
function show(elemid) {
document.getElementById(elemid).style.display = "block";
}
function hide(elemid) {
document.getElementById(elemid).style.display = "none";
}
Yes. jQuery. Will reduce your code to about 6 lines. :) http://jquery.com

Categories