Define map inside name space - javascript

Trying to define global map inside namespace and access that inside those namespace functions. but keep on getting Uncaught SyntaxError: Unexpected identifier. Appreciated If any one could guide me in defining global map inside namespace function and accessing.
var namespace = {
var mymap = new map();
cm: function () {
var childContainer = $("<div>");
namespace.myMap.set(cc, childContainer);
},
hm: function(ccm, data){
var cMenuItem = ccm.innerHTML;
for (var i = 0; i < data.c.length; ++i){
if ( cMenuItem === data.c[i]['l']){
namespace.Menus(data.c[i]);
namespace.myMap.get(cc);
}
}
}
};
Error comes in the first line var mymap = new map(); as Uncaught SyntaxError: Unexpected identifier

You are declaring a var inside an object. You cannot do that. You can only declare variables in a function.
What you did:
var namespace = {
var mymap = new map(); // <------ this line
cm: function () {
var childContainer = $("<div>");
namespace.myMap.set(cc, childContainer);
},
hm: function(ccm, data){
var cMenuItem = ccm.innerHTML;
for (var i = 0; i < data.c.length; ++i){
if ( cMenuItem === data.c[i]['l']){
namespace.Menus(data.c[i]);
namespace.myMap.get(cc);
}
}
}
};
What you should do:
var namespace = {
mymap: new map(); // <----- this line
cm: function () {
var childContainer = $("<div>");
namespace.myMap.set(cc, childContainer);
},
hm: function(ccm, data){
var cMenuItem = ccm.innerHTML;
for (var i = 0; i < data.c.length; ++i){
if ( cMenuItem === data.c[i]['l']){
namespace.Menus(data.c[i]);
namespace.myMap.get(cc);
}
}
}
};
Besides, map() is not Map(), as mentioned in comment.

Related

How to make a function assigning a value using assignment operator in jquery

Having the following function :
function ObjDataSet () {
this.header = "";
this.dataIdx = 0;
this.DataRows = [];
this.CountRow = 0;
}
....
ObjDataSet.prototype.NameString = function(argIdx, argName, argValue) {
var arrObj = this.DataRows[argIdx-1];
arrObj[argName] = argValue;
this.DataRows[argIdx-1] = arrObj;
};
And I am using this function like this after declaration:
var dataSet = new ObjDataSet();
dataSet.NameString(1, "CUST_KIND",document.searchForm.CUST_KIND.value);
But I would like to use this function like this using assignment operator :
dataSet.NameString(1, "CUST_KIND") = document.searchForm.CUST_KIND.value;
To use assignment operation, How to change "NameString" function?
I don't want to assign a value as a argument of function.
Thank you.
You cannot do what you are asking. The left hand side of an assignment must be a variable or a property of an object. The closest you can do is this:
dataSet.NameString(1).CUST_KIND = 'value';
Which assumes dataSet.NameString(1) returns an object that can have a property assigned to it. Here is a full demo:
var dataSet = setup();
// Log DataRows before and after assigning:
console.log( dataSet.DataRows );
dataSet.NameString(1).CUST_KIND = 'value';
console.log( dataSet.DataRows );
//////
// Prepare dataSet object with `DataRows[0] = {};`
function setup ( ) {
function ObjDataSet () {
this.header = "";
this.dataIdx = 0;
this.DataRows = [];
this.CountRow = 0;
}
ObjDataSet.prototype.NameString = function(argIdx, argName) {
return this.DataRows[argIdx-1];
};
const dataSet = new ObjDataSet;
dataSet.DataRows[0] = {};
return dataSet;
}

Javascript OOP private functions

I would like to create a constructor which can be instantiated with a json file which then is used by some private functions which in the end pass their results to a public function of the prototype. Is this the right approach?
Here more specific code:
//constructor
function queryArray(json){
this.json = json;
//init qry template with default values
function qryInit() {
var qryTemplate = {
//some stuff
}
return qryTemplate;
}
//generate array of request templates
function qryTempArray(json){
var template = qryInit();
var qryTempArray1 = [];
for(var i = 0; i < json.length; i++){
qryTempArray1.push({
'SearchIndex': json[i].SearchIndex,
'Title': json[i].Title,
'Keywords': json[i].Keywords,
'MinimumPrice': json[i].MinimumPrice,
'MaximumPrice': json[i].MaximumPrice,
'ResponseGroup': template.ResponseGroup,
'sort': template.sort
});
}
return qryTempArray1;
}
}
//function for finally building all the queries
queryArray.prototype.qryBuilder = function(){
var qryTempArray1 = [];
qryTempArray1 = qryTempArray(this.json);
//other stuff
}
If I call the qryBuilder function on an Object, I get an error
in the function qryTempArray at the json.length in the for loop (undefined).
Why that?
As the code is written above, I'm surprised you even get to the loop. It would seem you'd get undefined when you called qryBuilder();
I would expect something along the lines of the following to work.
//constructor
function queryArray(json) {
var self = this;
self.json = json;
//init qry template with default values
self.qryInit = function() {
var qryTemplate = {
//some stuff
}
return qryTemplate;
}
//generate array of request templates
self.qryTempArray = function(json) {
var template = self.qryInit();
var qryTempArray1 = [];
for (var i = 0; i < json.length; i++) {
qryTempArray1.push({
'SearchIndex': json[i].SearchIndex,
'Title': json[i].Title,
'Keywords': json[i].Keywords,
'MinimumPrice': json[i].MinimumPrice,
'MaximumPrice': json[i].MaximumPrice,
'ResponseGroup': template.ResponseGroup,
'sort': template.sort
});
}
return qryTempArray1;
}
return self;
}
queryArray.prototype.qryBuilder = function() {
var qryTempArray1 = [];
qryTempArray1 = this.qryTempArray(this.json);
return qryTempArray1;
}
var q = new queryArray([{
'SearchIndex': 0,
'Title': 'foo',
'Keywords': 'testing',
'MinimumPrice': 20,
'MaximumPrice': 40
}]);
console.log(q);
console.log(q.qryBuilder());

javascript push not working in array inside object

As you can see in the code, i tried to dynamically create arrays inside an object, it doesn't have a problem when debugging, but when i tried to use push method in the array it throws an error. By the way this is in google app script.
Push function not found in the object [object Object]: TypeError. (line 32, file
var LoopQuestGuildAchievementReward = function (spread_sheet, master_name, is_update) {
initializeBase(this, MasterBase, [spread_sheet, master_name, is_update]);
this.guild_achievement_columns = new Object();
this.create_guild_achievement_columns = function () {
var guild_achievement_coloumn_names = ['ids', 'event_ids', 'range_starts', 'range_ends', 'incentive_ids'];
for (var i = 0; i < guild_achievement_coloumn_names.length; i++) {
if (!this.guild_achievement_columns[guild_achievement_coloumn_names[i]]) {
this.guild_achievement_columns[guild_achievement_coloumn_names[i]] = {};
};
};
};
};
LoopQuestGuildAchievementReward.prototype.setMaster = function(option) {
if (!option || !option.summary_values || !option.batch_reward_values) {
throw "Argument exception.";
};
var event_id = option.summary_values[8][0];
var incentive_values = option.batch_reward_values;
var incentive_master_id = Commons.getIncentiveId(1, event_id, 5);
var data_row_number = searchRowNumberWrittenLavelInColumn_(incentive_values, 1, "reach num") + 1;
var guild_achievement_last_id = Commons.getLatestId("loop_quest_guild_achievement_reward", "ja") + 1;
this.create_guild_achievement_columns();
while (data_row_number < incentive_values.length && incentive_values[data_row_number][1] != "") {
var reach_number = incentive_values[data_row_number][1];
Logger.log(this.guild_achievement_columns.ids);
this.guild_achievement_columns.ids.push(guild_achievement_last_id); // <- this where the error message points (line no. 32)
// this.guild_achievement_columns.event_ids.push(event_id);
// this.guild_achievement_columns.range_starts.push(reach_number);
// this.guild_achievement_columns.range_ends.push(reach_number - 1);
// this.guild_achievement_columns.incentive_ids.push(incentive_master_id);
guild_achievement_last_id++;
incentive_master_id++;
data_row_number++;
}
Logger.log(this.guild_achievement_columns);
};
After asking my superior he mention that curly braces refer to objects and brackets refer to array.
Object: this.guild_achievement_columns[guild_achievement_coloumn_names[i]] = {};
Array: this.guild_achievement_columns[guild_achievement_coloumn_names[i]] = [];

Node Module Inheritance

I wrote the below listed module for an ExpressJS application. I now need to create a similar module with about 3 changed methods, and a few different instance variables. My plan is to create a superclass that has all the common (call it Common.js) and then require it for the two or more subclasses.
I generalized pointer to a tutorial might help me, but here are my specific questions:
the requires will be common, I suppose I put them in Common.js,
right?
I assume I should promote as many instance variables (the subclasses) into Common as possible?
The following could be a template fro the subclasses, with the Object.create coming at the top of the file
SubClass snippet:
var Common = require("./Common");
SubClass.prototype = Object.create(Common.prototype);
SubClass.prototype.subMethod = function() {....}
and also I assume that any submethod can refer to variables in the superclass, as well as new variables in the subclass, with as this.variableName,
BTW, how would I create new subClass instance variables?
Here is my original Code:
var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var tools = require("../tools/tools");
var Job = require("./falconJob");
var Batch = function (ticket) {
this.counts = [];
this.maxes = [];
this.errors = [];
this.done = [];
this.jobs = 0;
this.started = Date.now();
this.ended = Date.now();
this.jobBatch = {};
this.ticket = ticket;
this.batchRoot = null;
}
Batch.prototype.setup = function (frameList, req, next) {
this.group(frameList);
this.makeRoot(req, next);
}
Batch.prototype.group = function (list) {
_.forEach(list, function (obj) {
if (this.jobBatch[obj.type] == undefined) {
this.jobBatch[obj.type] = [];
}
this.jobBatch[obj.type].push(obj);
}, this);
};
Batch.prototype.makeRoot = function (req, next) {
var config = global.app.settings.config;
this.batchRoot = path.join(config.JobsPath, this.ticket);
var self = this;
fs.mkdir(this.batchRoot, function (err) {
if (err) return next(err);
var mapInfoFile = path.join(self.batchRoot, "MapInfo.json");
var mapInfo = {
Date: (new Date()).toISOString(),
Version: global.manifestVID,
Zoom: req.body.Zoom,
CenterLat: req.body.CenterLat,
CenterLon: req.body.CenterLon
};
fs.writeFile(mapInfoFile, tools.pretty(mapInfo), function (err) {
if (err) return next(err);
return next(null);
});
});
};
Batch.prototype.spawn = function () {
_.forEach(this.jobBatch, function (files, key) {
var job = new Job(key, files, this.batchRoot, this.ticket, this);
this.begin(job);
job.exec();
}, this);
};
Batch.prototype.count = function () {
var sum = 0;
for (var key in this.counts) {
sum += this.counts[key];
}
return sum;
}
Batch.prototype.total = function () {
var sum = 0;
for (var key in this.maxes) {
sum += this.maxes[key];
};
return sum;
}
Batch.prototype.fails = function () {
var sum = 0;
for (var key in this.errors) {
sum += (this.errors[key]) ? 1: 0;
};
return sum;
}
Batch.prototype.finished = function () {
var keylist = Object.keys(this.done);
if (keylist.length == 0) return false;
for (var key in this.done) {
if (this.done[key] == false) return false;
};
if (this.jobs != 0) return false;
return true;
}
Batch.prototype.rate = function () {
var speed = (this.count() * 1000) / (this.ended - this.started); // tiles / second
return speed;
}
Batch.prototype.begin = function (job) {
var type = job.type;
this.jobs++;
this.counts[type] = 0;
this.maxes[type] = 0;
this.errors[type] = false;
this.done[type] = false;
}
Batch.prototype.end = function (job) {
type = job.type;
this.jobs--;
this.errors[type] = job.errors;
this.done[type] = true;
}
Batch.prototype.update = function (status) {
type = status.layer;
this.ended = Date.now();
this.counts[type] = status.tilesCount;
this.maxes[type] = status.tilesMax;
this.done[type] = status.done;
}
module.exports = Batch;
I am surprised, no one answered. Well I have a solution, and a few tips. First, read the Mozilla developer page about an introduction to javascript inheritance: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Here is how I structured my "sub-module" which I can just require in and it will pull in the super-module, and then subclass it.
var _ = require('lodash'); // require any additional modules that your sub module needs
var BatchRoot = require('./Batch'); // require the super-module with the superclass
var Job = require("./falconJob"); // another module that I need
var Batch = function (ticket) {
BatchRoot.call(this, ticket); // The superclass constructor takes "ticket" as a param
// define new subclass instance variables here, e.g. this.foobar = 33;
}
Batch.prototype = new BatchRoot(); // This does the subclassing
Batch.prototype.constructor = BatchRoot; // MDN says to do this to correct the constructor pointer because it points to Batch
// this is a new subclass function, notice that I use Job which is only defined here
Batch.prototype.spawn = function () {
_.forEach(this.jobBatch, function (files, key) {
var job = new Job(key, files, this.batchRoot, this.ticket, this);
this.begin(job);
job.exec();
}, this);
};
module.exports = Batch;

passing array to Constructor function and keep it public

here is my code :
var BoxUtility = function() {
var boxList = Array.prototype.pop.apply(arguments);
};
Object.defineProperties(BoxUtility, {
totalArea: {
value: function(){
var x = 0;
for(var i = 0, len = boxList.length; i <= len - 1; i++){
x = x + boxList[i].area;
};
return x;
}
}
});
I'm trying to achieve this syntax for my Code :
var boxArray = [box01, box02, box03];
box are objects, box01.area => boxes have area property
var newElement = new BoxUtility(boxArray);
alert(newElement.totalArea);
I WANT TO SEE THE RESULT AS I EXPECT but I think boxList is in another scope
How can I reach it in defineProperties
You have to assign the value to a property of this in your constructor.
var BoxUtility = function() {
// this.boxList
this.boxList = Array.prototype.pop.apply(arguments);
};
// instance methods go on the prototype of the constructor
Object.defineProperties(BoxUtility.prototype, {
totalArea: {
// use get, instead of value, to execute this function when
// we access the property.
get: function(){
var x = 0;
// this.boxList
for(var i = 0, len = this.boxList.length; i <= len - 1; i++){
x = x + this.boxList[i].area;
};
return x;
}
}
});
var boxUtil = new BoxUtility([{area:123}, {area:456}]);
console.log(boxUtil.totalArea); // 579
Variable scope is always at the function level. So you declared a local variable that is only usable inside your constructor function. But every time you call the constructor function you get a new object (this). You add properties to this in order to have those properties accessible in your instance methods on the prototype.
this works
var BoxUtility = function() {
this.boxList = Array.prototype.pop.apply(arguments);
Object.defineProperties(this, {
totalArea: {
get: function(){
var x = 0;
for(var i = 0, len = this.boxList.length; i <= len - 1; i++){
x = x + this.boxList[i].area;
};
return x;
}
}
});};
var y = new BoxUtility(boxArray);
alert(y.totalArea)
This is simple way to pass array as argument in constructer and declare function prototype for public access.
function BoxUtility(boxArray) {
this.boxArray = boxArray;
this.len = boxArray.length;
}
Color.prototype.getAverage = function () {
var sum = 0;
for(let i = 0;i<this.len;i++){
sum+=this.boxArray[i];
}
return parseInt(sum);
};
var red = new BoxUtility(boxArray);
alert(red.getAverage());

Categories

Resources