creating instances dynamic javascript - javascript

I have a function with some methods.
function acpwindow(){
this.gui=function(){
//some stuff
}
this.update=function(){
//some stuff
}
}
Now i would like to create multiple instances of that function.
i have a button that create windows. onclick new window will trigger;
function createwindow(){
var object1= new acpwindow();
/*
**Here is a problem I have, How to maintain the objects unique.**
*/
}
When user makes some actions on windows gui those requests sent to server and then server will respond for those request.
Now my other issue is how to how to update particular window according to the response.
The only hope i have is I will generate a unique UUID for each request and the same will return in the response.

I think if you create some kind of window manager to manage the windows you create, it might be easier to send and process requests. Something like:
http://jsfiddle.net/v3T94/1/
And in the example, if it's necessary, you can use the id property. Otherwise, if you keep track of the reference when calling sendRequest, you should be able to perform what you want on the correct acpwindow

The standard way to keep this kind of connection is using closures.
For example if you write
function make_timer()
{
var x = document.createElement("div");
var count = 0;
setInterval(function(){
count += 1;
x.textContent = count;
}, 1000);
return x;
}
every call to make_timer will create an independent DOM node in which the content every second will be incremented. But how can the timer callback remember which is the node that needs to be incremented? The answer is that what is passed to setInterval indeed is not a function but a closure, i.e. a function plus some variables (count and x in this case).
Languages like Java or C++ don't have this concept, but that happens is the the function that is created also it's said to "capture" local variables if they are from an outer scope and it will keep them "alive" even if the outer function that ceated them ends (i.e. when the function make_counter exits).
The very same can be used for ajax requests. What you normally do is just passing the window object to the function that submits the request and a callback closures will be used as completion and error callbacks. The closures will have access to the respective window objects when the answers come back from the server.
Edit
If you really want to use IDs then of course you can... in your example they are store in an array so the array must be traversed to look for the exact ID...
var windowid=$("#guiid").val();
for (var i=0; i<window_manager.windows.length; i++)
if (window_manager.windows[i].id == windowid)
window_manager.windows[i].gui();
Using an object instead of an array would be better because in that case the search could be reduced to a single like:
var windowid=$("#guiid").val();
window_manager.windows[windowid].gui();
Note however that in many cases numeric IDs for are not needed in Javascript because where you would store the window id you could store instead the reference to the window object itself, and for callbacks there is no need of complex machinery for providing context (like it's necessary in C++ or Java) because you have closures.

Related

Standard way to get a pre-calculated variable/property from a JS function's prototype

I'm looking for the standard way to calculate a variable once, then access it within the scope of every execution of a function, without relying on global variables.
This seems like a standard use of prototype properties (variables) - but every example I can find on JS prototypes is based on prototype methods (functions). The only thing I can find about setting properties / variables in a prototype is a question from someone who also couldn't find any information about these, asking if it's good or bad practice (tldr: it's fine, but remember it's rarely worth sacrificing readability for tiny performance gains).
I've got a way to set and get prototype properties that works, but feels clunky as it depends on a reference to the function (essentially var prop = thisfunctionname.prototype.someprop). Since I found it through trial and error, I'd like to ask if there's a cleaner, more standard way to get these prototype properties from within the function, without going back up to the scope around the function and getting the function from there?
Here's a simplified light-hearted example: an imaginary jQuery plugin that adds a number to another number then returns it in a sentence with the user's name. We want to ask the user their name only once, then store that name for re-use within scope:
(function($) {
var sum = function( num1,num2 ) {
var result = num1 + num2;
// This works, but seems clunky since it depends on the variable `sum`
// from the scope around this function - is there a better way?
var name = sum.prototype.name;
$(this).text( num1+' plus '+num2+' is '+result+', '+name+'.');
return $(this);
};
var name = prompt('Please enter your name','');
// Is there a better way to set this default variable to be accessible
// in all calls to this function?
sum.prototype.name = name;
$.fn.basicArithmetic = sum;
})(jQuery);
// end of plugin. Example usage...
$('<p/>').basicArithmetic(1,5).appendTo('body');
$('<p/>').basicArithmetic(2,2).appendTo('body');
$('<p/>').basicArithmetic(25,30).appendTo('body');
$('<p/>').basicArithmetic(92.3,15.17).appendTo('body');
Live jsbin example. More realistic real-life use cases would be when the calculation for the property is expensive in memory usage, or destructive (e.g. requires changing the DOM during calculation).
Two different answers, really:
The usual way is to use a variable within a scoping function (you already have one handy in your example); no prototypes involved at all.
(function($) {
var name;
name = prompt('Please enter your name','');
function sum( num1,num2 ) {
var result = num1 + num2;
$(this).text( num1+' plus '+num2+' is '+result+', '+name+'.');
return $(this);
}
$.fn.basicArithmetic = sum;
})(jQuery);
Updated JSBin Example | Source
(Side note: I also changed your anonymous function expression into a named function declaration, but it doesn't really matter in this case.)
The usual way in a jQuery plug-in is to store the data on the element(s) the plug-in is being applied to. That doesn't work for the example you gave, which requires that the data be global to the plug-in, but normally (not always, just normally) plug-ins keep only instance-specific information, which you'd normally store on elements (probably via the data function).

Prevent JavaScript Injection on Timer

I am making a browser game where every 10 seconds, i is incremented, and the points algorithm uses i to determine the number of points awarded. The obvious way (to me) to do this is to use setInterval(10000) for the timer, and run the points calculation inside of the function.
How do I prevent a JavaScript injection that increases i, making the app think that the user has actually been playing for longer than he really has?
I am using Firebase as the back-end. As a PHP programmer, I would normally just do server-side validation of the player's points when he submits them by checking start & end times. I suppose I can do this in Firebase as well, so I probably just answered my own question...
Still, is there a way to just prevent a JavaScript injection? (Prevention, not server-side Detection).
You can make variables essentially private, which means that it will be impossible for the user to change them through plain JS injection. But that won't stop someone from intercepting your Javascript with a debugger, from intercepting your communication between client and server, or from doing all sorts of other fiddling.
To make a variable private, just include it inside a function, execute that function, and return something that includes a function referencing that variable. This is called a closure. It's quite easy to do.
In this fiddle there is a counter variable that is updated every second (not every ten seconds -- I'm in a hurry! :-) ) and another variable, basePoints that together add to the current score.
Publicly exposed is a function that allows you to add to the basePoints value, but nothing allows you to add to the counter. I don't think you can do that without getting inside the JS engine (as a debugger does.) The main point is that there is no way within Javascript to update the counter variable.
var app = this.app = (function() {
var counter = 0;
var basePoints = 0;
var div = document.getElementById("score");
var addPoints = function(nbr) {
basePoints += nbr;
display();
};
document.getElementById("add20").onclick = function() {
addPoints(20);
};
var display = function() {
var points = counter + basePoints;
div.innerHTML = points + " points";
};
setInterval(function() {
counter += 1;
display();
}, 1000);
return {
addPoints: addPoints
};
}());​
You can prevent simple manipulation of the variable via things like bookmarklets by just making sure that the variable is internal to a function context and is NOT a global variable and not accessible from the global scope. That can be as simple as putting it into a self executing function context like this:
(function() {
var i;
// code that uses i
setTimeout(function() {
more code that uses i
}, 1000);
})();
In this case, only code inside that first function block can get to the variable i.
Note, as others have said, this doesn't prevent more complicated manipulations that actually change the source javascript before the page executes it or break in the debugger and manipulate things there as there is no way to prevent those, but it does prevent the simplest ways of reaching into a page and changing the variable (like from a bookmarklet).
There is virtually no way to prevent any sort of highscores hacking by calculating the value on the client side and subsequent push to the server side. Only obfuscation and different tricks can make the hacking more or less complicated, but they cannot prevent it at all. That is why server side validation or event better server side calculation is preferred.

Edit Javascript function

Is it possible to edit a JavaScript function after the page has loaded?
I want to edit a function dynamically after Loading.
You can't edit a function, but you can replace it, e.g.:
var myFunc = function() { return "Hello World"; };
myFunc = function() { return "Goodbye"; };
javascript functions are objects, so can be replaced by setting a new value. Is this what you mean?
Unless you are trying to hack some code that doesn't belong to you, the better solution is to write a more flexible initial javascript function who's behavior can be adapted based on conditions (parameters passed, environment, other state, data fetched from other sources, etc...). Then, the one function you have can be written once initially to handle all your different circumstances.
You can even use design patterns such as passing in callback functions that can be used to adapt the behavior at runtime. If you desire many callbacks, you can pass in an object that has a number of different optional methods and call those during your function. In this way you can significantly alter the behavior of the main function without ever changing it's code by passing in different callback functions.
For example, let's assume we have a parsing function that takes some tagged data structure as input and returns an array of results. We want to be able to modify the behavior of this parsing function by passing in callbacks. So, we write the parsing function to take a callback object. That callback object contains one or more methods (all of which are optional) and a state variable that is passed to each callback. Anyone who has worked with ajax or any asynchronous networking in Javascript will recognize the callback object concept. Here's some pseudo code for such a process that shows how the callback object can be used. A real function would obviously be a lot more involved than this one, but it hopefully illustrates the concept:
function parseMyData(data, callbacks) {
var output = []; // output we accumulate
var currentTag;
callbacks = callbacks || {}; // make the callbacks object optional
// do any preprocessing that the caller specified
if (callbacks.preProcessData) {
data = callbacks.preProcessData(data, callbacks.state);
}
[[code to parse to the first tag in the data (after doing so currentTag contains the tag we just parsed)]]
// give our callback object the opportunity to do something to this tag or return null to skip it
if (callbacks.preProcessTag {
currentTag = callbacks.preprocessTag(currentTag, callbacks.state);
}
if (currentTag) {
[[code here for the default processing of the tag that will push results into the output array]]
}
return(output);
}
If you want to add an action to the existing function you can "hijack" it by putting it in a temporary variable and calling it within your overwritten function. E.g.
// The original function.
function sayName(name) {
alert(name);
}
// Temporary variable for original function.
var __sayHello = sayName;
// Overwrite the original function, adding extra actions.
sayName = function(name) {
alert('Hello');
// Call the original function using its temporary variable.
__sayHello(name);
}
// Call the overwritten function.
sayName('Bob');
How to edit a function - 101.
If we reconsider that editing a function at runtime is not absolutely changing the guts of the function, but rather changing what the function guts are digesting, then I would say functions are already built to do just that.
example 1 - The guts cannot be changed.
function one(){
return true;
}
// one() => true;
// Note: We could still change the output without changing the guts.
// !one() => false;
example 2 = The guts can be created to digest a dynamic call.
function one(payload){
return payload;
}
// one(true) => true;
// one(false) => false;
// one('whatever I want to feed the guts to digest');
// => 'whatever I want to feed the guts to digest';
These are quite simple examples, but since you did not provide any real examples as to what you are trying to do, we have to assume you are attempting normal patterns of programming.
Considering NORMAL patterns of programming, it wouldn't be the function itself that needs to change, rather how you are calling it.
example 3 - Give the choice of which function to the caller.
function firstChoice(payload){
return http.post(payload);
}
function secondChoice(choice){
return `Do something else with ${choice}`;
}
// And where you make the choice, perhaps after a click event handler...
function onClick(choice, payload){
choice ? firstChoice(payload) : secondChoice(choice);
}
Functions are supposed to be small bricks with which you build logic. Give them something small to do, then select between them based on your logic.
To answer your question, in my opinion, assuming normal programming needs...
"Is it possible to edit a JavaScript function after the page has loaded?" YES.
Use arguments in your function definition to add the dynamic ability to suit your needs.

What is the proper way to control related objects in javascript?

I'm new to object oriented programming and am slowly learning how to apply it to javascript. So please bear with me. :)
I have two basic objects:
"record" which contains methods for editing a single record from a recordset. (create, save, load, etc.)
"recordList" which contains methods for outputting a paginated list of record titles.
I would like for these objects to be able to work together. For example, if record.save() is called, recordList.refresh() is also called, so that the paginated list reflects the updated data.
To accomplish this, I have created a third object "control" which contains instances of both "record" and "recordList". I am using "control" in the following fashion:
control = {}
control.record = object.create("record");
control.recordList = object.create("recordList");
control.save = function() {
this.record.save();
this.recordList.refresh();
};
This works. But I am wondering, is it proper? (I want to be sure I am not violating any of the rules of OO design in doing this.) Is there a better way?
Thanks in advance for your help.
Speaking from an OOP perspective, I don't think a record would save itself. A record in a database is simply data, and the database itself is what does things with that data, whether it's saving or loading or etc. That being said I'd make record be simply an object that holds data and would create a recordset object for interacting with the data. Within that recordset object you could put your recordList and update it accordingly. Something like:
var recordset = function() {
var me = this;
var currentRecord = object.create("record");
var recordList = object.create("recordList");
me.save = function() {
//Insert record.save code here
recordList.refresh();
};
};
Something to note about that code. In that setup currentRecord and recordList can't be accessed from outside the function and therefore you have encapsulation, one of the hallmarks of OOP. This is because the recordset function is a closure that "closes over" all variables within, meaning that every function within has access to the variables within the scope of recordset.
You could let the outside world get access through get or set functions:
me.getRecordList = function() {
return recordList.getArray(); //Not generally a good idea to simply return your internal object
};
Your solution is fine. Two minor suggestions for improvement
Use a more specific name than control (even 'recordControl' is ok). You may end up with lots of controls for different feature sets.
Use an object literal to create the entire object. Keeps your code tidier and more readable (and saves a few bytes)
(apologies for lack of spacing - editor not doing what I want it to do!)
recordControl = {
record : object.create("record"),
recordList : object.create("recordList"),
save : function() {
this.record.save();
this.recordList.refresh();
}
}
If it's one thing I've learned over time, it is that following any paradigm to the letter will result in more frustration and difficulty than taking the concept as far as you can go and using common sense to dictate your deviations.
That said, your solution will work fine and it's normal to create a container class for multiple objects of varying types that are coupled. If you want a different way to handle it, check out Client Event Pooling. The only thing that I can say about what you've done is to be sure you're using object.create the way it was intended.
Using this method you can create an event, which when triggered will perform a series of other commands that are associated with your event. I have used this with great success in all sorts of applications, from the intended event hooking to simplifying inline javascript injections after a postback.
Good luck.
why don't you provide your recordList into record?
var record = object.create("record");
record.recordList = object.create('recordList');
record.save = function(){
/*
do something
*/
this.recordList.refresh();
}

Race Condition because of multiple AJAX requests

my problem is the following. I wrote a class AJAXEngine, which creates in the constructor a new XMLHttpRequest object. The class contains a method called responseAnalyser, which is called when the "onreadystatechange" of the XMLHttpRequest object has changed.
So now I created lets say 4 instances of AJAXEngine => 4 XMLHttpRequest objects.
Now I have another class DataRequester, which has an array-attribute dataReq, which holds the instances of AJAXEngine. There is only one instance of DataReqeuster in the whole program!
DataRequester has a function called callWhenFinished. The function is called, by the function
responseAnalyser of AJAXEngine and decrements a variable of the DataRequester instance.
But, I think there happen race conditions. How could I prefent them in JavaScript?
function AJAXEngine
{
this.httpReqObj = //create new XMLHttpRequest Object
this.obj;
this.func;
}
AJAXEngine.prototype.responseAnalyser = function()
{
if(this.httpReqObj.readState == 4)
{
this.func.call(this.obj);
}
}
AJAXEngine.prototype.fireReq = function(o, f)
{
this.obj = o;
this.func = f;
// fire ajax req
}
function DataRequester()
{
this.dataReq = new Array();
this.test = 4;
for(var i = 0; i < 4; i ++)
{
this.dataReq[i] = new AJAXEngine();
}
}
DataRequester.prototype.callWhenFinished = function()
{
this.test --;
}
Not sure if this would help, but it looks like you're trying to create a managed connection pool. I did one a few years ago that still works fine here:
DP_RequestPool Library
The pool ensures that requests are made in the order you've provided them (although, of course, they may be returned in any order based on performance) using as many simultaneous requests as you define (subject to system limitations). You can instantiate multiple pools for different purposes.
If nothing else this might give you some ideas.
First of all: most of AJAX-oriented browsers support convention "only 2 simultaneous requests to the same domain". So if you start 4 then 2 of them will be pended.
You DataReqeuster /singleton/ can have array of variable 'test', so instead of share single variable across multiple instances, create multiple instances of data. So to calculate result you will need to sum 'test' array.
You would need to implement a makeshift mutex (the idea is that a heuristic would check for a bool and set it to true if it's false then do body, otherwise sleep(settimeout?) - this is obviously a pretty bad heuristic that nobody would implement as it is not thread safe, but that's the general concept of how you would deal with the race conditions anyway).
I believe there at least one example of creating a mutex on the web, but I have not looked over it in detail - it has some detractors, but I am unaware of another way to achieve 'thread safety' in javascript. I haven't ever needed to implement js 'thread-safety', but that's I start looking if I had to deal with race conditions in javascript.
You can't do a mutex in javascript simply because there really is no built in sleep function available.
See: Is there an equivalent Javascript or Jquery sleep function?
Also, there is no way to ensure that the boolean flag in your mutex isn't being accessed at the same time as another thread, the boolean itself then needs a mutex... and so on and so on. You would need something like Synchronized keyword in java to be available in javascript and this simply doesn't exist. I have had situations where I was worried about thread safety, but when with the code anyway with an alternative plan if an error occurred but that has yet to happen.
So my advice, is if your getting an error, its probably not because of a race condition.

Categories