I'm trying to figure out a way to create a new class instance when values are passed from an Android app to a JavaScript program. I know JS doesn't use classes, but there are ways to use functions in a similar way.
When a user presses a button in the Android app, I want to send a randomly generated ID (which I have created) to a database that stores the ID (and user info), and then have a JS program pull the ID and create a new instance for that ID. There will be multiple users accessing this at the same time, so I need to create a new instance each time a user presses the button. It will also send the ID, latitude, longitude, and time to a separate database where the location will be updated and stored every second.
For example, if 'user1' presses the button, the id (user1) will be sent to DB_1 and the ID, latitude, longitude, and timestamp will be sent to DB_2. The JS will be alerted of the new user and create an instance for user1, and then will use the ID as a variable to search DB_2 for coordinates every second. This way, if there are multiple users, each class will only search DB_2 for coordinates that pertain to that user. I need to do this because I must be able to track multiple users at the same time (and in real time) with a Google Map on the web. Let me know if you have any suggestions!
Thanks
If all you want to do is make a JavaScript object with it's own private variables then try something like
function User(id) {
this.id = id;
};
You can then use prototype functions.
User.prototype.getId = function() {
return this.Id;
};
Now you have an object with a private variable id and a getter for that variable.
You can create instances of the object like this
var user1 = new User(id1);
var user2 = new User(id2);
var user1Id = user1.getId();
var user2Id = user2.getId();
I like to use the prototype pattern because it keeps things safe and organized but you do end up using "this" a lot. There are other patterns that achieve basically the same thing, which you may prefer to use but I can't think if the name of any of them right now.
In the construct using
function User(id) {
this.id = id;
};
User.prototype.getId = function() {
return this.Id;
};
Is sort of similar to doing this in Java except without type safety.
public class User{
private int id;
public User(int id){
this.id = id;
}
public int getUserId(){
return this.id;
}
}
Of course there is a pretty big difference between the inner workings of compiled Java and interpreted JavaScript but the above method gives you a similar OO effect.
If you use this method and end up with some errors, in all probability you have left out a "this" somewhere. Every variable in the prototype function that is part of the object must have the "this." prefix.
Hope that's something along the lines of what you were looking for.
Related
Normally what we do is like
const hash = new Map()
hash.set(key,value)
And when we want to retrieve the information just
hash.get(specificKey)
One of the benefits that Map has is that we can put whatever we want as key or value.
I'm trying to set a multiple value of keys on the "key" part of the map, that's not the problem is later when I want to get the information
Example:
[
{name:"Pedro",email:"test1#gmail.com"},
{name:"Anibal",email:"test2#gmail.com"},
]
I want to create the key of the map with both properties of the object (name, email), and the value is ALL the iterated register so...
const hash = new Map()
for (register of registers) {
const { name, email } = register
hash.set([name, email], register)
}
The problem is when I want to GET the register by one of the properties on the key.
We know that the key could be ["Pedro","test1#gmail.com]
How I can get the value of the Map if the key I want to get could be just "Pedro" or just "test1#gmail.com"
It is possible? :(
Thank you
___________________-
Answer to #Kevin Kinney
Thank you for answering. The idea that I want to do is to avoid this;
I dont want to have a find inside the map. Any different approach?
One idea, if you know only a few of the properties would be used as keys
const hash = new Map()
for (register of registers) {
const { name, email } = register
hash.set(name, register)
hash.set(email, register)
}
This will allow fast access to the value in the map, but increases the memory usage.
Otherwise I don't think a hashmap is the right idea if you don't know what key you will be expecting to use.
No, this is not possible
You want access in a non-standard way so what you can do is create two mappings for each value. One goes from pedro and one goes from test1#gmail.com
Then when you need to retrieve the value you can get it by either
I have two Knockout Model instances (ModelInstance1 and ModelInstance2). For both instances all bindings are already applied and page is loaded with two different forms.
One form is visible for user and allows user to do inline editing. FOr this form I use ModelInstance1.
Another form is modal form that appears on Edit button click. This form uses ModelInstance2. If user clicks Cancel, then no values are saved to database and modal form is closed.
Now I need on my custom event (imagine as it would be button click) to copy all values from one instance to another.
Of course, I can do like this manually:
ModelInstance2.FirstName(ModelInstance2.FirstName());
ModelInstance2.LastName(ModelInstance2.LastName());
etc.
but is there any other way to do this?
Take into account that my Model contains observables, observable arrays, computed and subscriptions.
Write the constructor function for your model so that it can take a plain object as an initializer. Then you can clone a model by doing
var modelInstance2=new Model(ko.utils.parseJSON(ko.toJSON(modelInstance1)));
You need to serialize to JSON and then parse the result to get a deep copy (properties that are reference types like objects and arrays are actual copies and not references to the original). If you did
var modelInstance2=new Model(ko.toJS(modelInstance1));
then you'd get a shallow copy and changing any reference-type property in modelInstance2 would also change it in modelInstance1.
How about...
var Model = function (firstName, lastName) {
var self = this;
self.FirstName = ko.observable(firstName);
self.LastName = ko.observable(lastName);
self.clone = function () {
return new Model(this.FirstName(), this.LastName());
};
}
var instance1 = new Model('Jon', 'Smith');
var instance2 = instance1.clone();
If you had the knockout mapping extension available you could always do this....
var temp = ko.toJS(instance1);
var instance2 = ko.mapping.fromJS(temp);
http://knockoutjs.com/documentation/plugins-mapping.html
If you dont want to maintain a method that clones the object then mapping is a good option, I can think of no other way to handle it. These seem to be your options.
As shown in this example
javascript-use-variable-as-object-name
I am using eval to use a DOM attribute to select an element from an array. Though there is no direct way for the user to change the input, I want to be as secure as possible and make sure that the variable is indeed an integer before I evaluated it.
Which of the following would be the best, most secure, way?
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(!isNaN(new Number(id))){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
or
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(parseInt(id)){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
More, but not required info:
Basically I am pulling down a large JSON string from online, containing an array of records. Upon building a table from the info using a for statement ( for(i in array) ), I push each row into an array called rowsHolder and give the tr an attribute of record-id="i". Then when the user clicks the row, I call the method you see above. I am using PhoneGap with JQuery Mobile.
As always, thanks for the input
-D
There is absolutely no reason to use eval here.
If your id is kind of a number, use parseFloat(id) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is an integer, use parseInt(id, 10) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is a string, just let it be a string. The property name you use it for would be one anyway.
To be honest, I'm not quite sure where to start with this question.
I'll describe the situation: I am in the process of making a level editor for an HTML5 game. The level editor is already functional - now I would like to save/load levels created with this editor.
Since this is all being done in Javascript (the level editor as well as the game), I was thinking of having the save simply convert the level to a JSON and the load, well... un-jsonify it.
The problem is - the level contains several types of objects (several different types of entities, several types of animation objects, etc...) Right now, every time I want to add an object to the game I have to write an unjsonify method specifically for that object and then modify the level object's unjsonify method so it can handle unjsonifying the newly defined type of object.
I can't simply use JSON.parse because that just returns an object with the same keys and values as the original had, but it is not actually an object of that class/prototype. My question is, then, is there a correct way to do this that does not require having to continuously modify the code every time I want to add a new type of object to the game?
I would create serialise/deserialise methods on each of your objects to put their state into JSON objects and recover it from them. Compound objects would recursively serialise/deserialise their children. To give an example:
function Player {
this.weapon = new Weapon();
}
Player.prototype.serialise = function () {
return {'type': 'Player', weapon: this.weapon.serialise()};
}
Player.deserialise = function(json_object) {
var player = new Player();
player.weapon = Weapon.deserialise(json.weapon);
return player;
}
Obviously in real code you would have checks to make sure you were getting the types of objects that you expect. Arrays and simple hash objects could be simply copied during serialisation/deserialisation though their children will often need to be recursed over.
I'm using pines notify (somewhat irrelevant to my issue, I imagine) to create notifications on the change event of a drop down list. On the server side, the change is saved to a database, then when the save is complete - I wish to remove the notification (or do something else depending on the result).
The problem is in creating the notification object in a way that I can later reference it (to remove it).
My intended solution would obtain the id of the dropdownlist, prepend 'pn' to it and use that as the variable name, much like
var pnid = 'pn' + $('#mydropdown').attr('id');
notifications[pnid] = createNotification();
In the codebehind I can create javascript code knowing what the notification object will be called. However I'm struggling with my 'notifications' object.. I've tried this[notifications], window[notifications] etc. to no avail (ie I cannot later reference this object to interact with it) . I'm creating that object outside of any functions like so
var notifications = {};
Am I going about this the completely wrong way?
You can use this line before reaching notifications object.
window.notifications = window.notifications || {};
This will help you create the object if it is undefined and it will also prevent you from overriding it if it already exists.
Note : I assume you have to use this object as a global variable.