Modifying 'global' object in Node.js - namespaces

Is there any reason why the following code:
global.myNamespace = {};
fails to add 'myNamespace' to the global object, i.e.
typeof global.myNamespace
returns
'undefined'
Node.Js 0.3.1-pre

You're probably trying this code in the node-repl. The repl is special in that every command submitted gets a new context. That means a brand new global object. Any of your variables in the old context can still be found, but all of the global js variables are replaced with brand new ones. That includes global, Object, Array, etc.
What you're doing will work fine in a script. Just not in the repl.

Related

why fabricjs kclass fromobject returning undefined on new version?

yesterday i have changed fabricjs version in our application. suddenly kclass.fromObject returning undefined.
my previous version is 1.7.22 and currently using 3.6.1 https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.1/fabric.min.js
kclass.fromobject returning undefined. but objects[i] has data.
> var klass = fabric.util.getKlass(objects[i].type);
> console.log(klass.fromObject(objects[i])); //returning undefined on 3.6.1
> fabricObj.add(klass.fromObject(objects[i]));
could you please let me know how to fix this issue?
Here is the screenshot
Your objects array contains just plain javascript objects that represent serialized Fabric objects (like path, circles, whatever).
Before rendering these plain javascript objects you need to transform them in Fabric objects. This process is called deserialization.
Your code does it, but only the if the async property of the variable klass is true.
It happens here:
var klass = fabric.util.getKlass(objects[i].type);
if (klass.async) {
klass.fromObject(objects[i], function (img) {
canvas1.add(img);
});
}
The object is deserialized, passed as an argument to the callback function and then added to the canvas, and this is great.
The problem is in the else branch of your conditional, where nothing of that happens. The only code present is this:
else {
console.log(objects[i]);
canvas1.add((objects[i]));
}
Here you are trying to add the plain object to the canvas, and that triggers an error.
One simple solution is to remove the if / else and always execute the deserialization step. If for other reasons you need to maintain the if / else conditional, you can simply deserialize the object in the else path too.
Here is a working Fiddle that preserves the conditional.
Why did it work in the previous version of Fabric? It is hard to say. Maybe that type of object was marked as async, so triggering the right path. Or maybe the canvas.add method was automatically deserializing javascript objects.

JSON Compatible Output of Whole Object and Their Invisible Properties in Node

const TelegramBot= require('./telegram-bot') // It's currently only local.
var bot = new TelegramBot()
console.log(bot)
// This does not print a complete JSON of the object. It misses stuff like
constructor, method, prototype and super_.
Is there some way or npm module that prints a JSON compatible output of the object?
My only work around so far is console logging it out like this and repeatedly checking the log and printing out another but I think it'll be a lot of easier by having a JSON export and using a JSON online viewer that views like a directory tree.
console.log(`
TelegramBot:
> ${Object.getOwnPropertyNames(TelegramBot)}
TelegramBot.prototype:
> ${Object.getOwnPropertyNames(TelegramBot.prototype)}
TelegramBot.prototype.constructor:
> ${Object.getOwnPropertyNames(TelegramBot.prototype.constructor)}
TelegramBot.prototype.constructor.super_:
> ${Object.getOwnPropertyNames(TelegramBot.prototype.constructor.super_)}
`)
I'm aware functions can't be seen with JSON.parse(). I don't mind if they appear as a string like "Anonymous Function()" or "FunctionWithAName()". Or something like this.
I'm doing this since I'm having another go trying to learn prototypes and I've used util.inherits(TelegramBot, EventEmitter) in the TelegramBot object.
To avoid name clashes between TelegramBot methods I've made and the super class of EventEmitter names. I'd like to keep a clear view of the whole object structure. Or do I not have to worry since they use this variable shadowing thing? If I'm correct it checks the object's instance first, then it's prototype. Not sure if EventEmitter prototype checked first or TelegramBot's.

Why is native .bind() so slow?

I recently came across this issue. For a project I'm working on, we were using .bind() way too often and it actually hit the performance quite hard considering that we only have 16ms for the rendering loop to do things.
So I did some jsperf and noticed that calling a bound function (besides of the extra garbage) is way slower than calling an unbound function or using .call on a function.
I literally changed every piece of code to avoid bindings and to use .call/.apply instead. Ding this i not only spawned less functions but also increased the performance of my app a great deal.
However, I was unsatisfied with this and wrote a new way of binding functions.
https://github.com/SebastianNette/FastBind
This is overwriting the native bind method with a .call/.apply approach.
And it runs 96% faster.
Doing some testings on nodejs is came to these results:
Calling a bound function is 20 times slower than calling an unbound function.
Calling a bound function with my own approach takes only 2 times the time of the unbound call.
So I was wondering what is wrong with the native binding function. Why does it behave like that? And which would be the best way to deal with that issue.
Most of my app code is now written like that:
var scope = this;
this.boundFn = function(a,b,c) { return scope.fn(a,b,c); };
Or even
this.callback = fn;
this.context = context;
this.callback.call(this.context);
I do prefer the latter because it doesn't spawn any new functions. However, sometimes I just do have to bind. (handlers, timers, etc).
My educated guess is that it makes a clone of the object you are using but replaces the underlying prototype of object. Instead of using a generic precompiled object from the page rendered code it now has to take two things:
The passed variable thats to be come this. analyse it, clone it. then inject the specified function thats to be called into the new object. Then execute the function in the new object. afterwards if no longer called clean it up.
The more complex and more scoping loops an object has the long the bind will take because the engine needs to traverse the scope tree of all functions and parameters to see what needs to be copied.
You are already using scoping, which I strongly advice. It is less memory intense and the engine does not have to copy the objects and then call the functions. And you get the added benefit that you can access properties from both objects.
In my experience binding is never truly needed. Just use setters and getters for properties, otherwise the scoped variables won't always change in the main object.
Take for example this snippet
function domagic() {
this.myproperty = "Hello ";
}
domagic.prototype = {
perform:function(){
var that = this;
var hello = "World";
setTimeout(function(){
// this in this contect is whatever runs timeout. not domagic
// I use this for jQuery and my own objects to get best
// of both worlds, but I always post a comment in a scope
// to remind myself what this and that refers to.
window.alert(that.myproperty+hello);
that.set("Goodbye ");
},2000);
},
set : function(what) {
this.myproperty = what;
}
};
magic = new domagic();
magic.perform();
setTimeout(function(){magic.perform();},2000);

What is the difference between 'Doc root var' and 'Owner var' in CocosBuilder

In CocosBuilder, there is a Code Connections section. At second line, it has three options: Don't Assign, Doc root var and Owner var.
Sometimes, I got a error when I was selecting Owner var, but it works fine after I changed it to Doc root var.
I google a lot, but can't find a satisfied answer.
Does anyone can explain the difference clear?
Don't assign simply means that you are not using the Code Connections.
Doc root var means that you are connecting a custom cocos2d class. This will glue/connect the object in your document (CCB stage/file) to your code. This option is convenient but you must make sure that root node's controller object is provided.
Sometimes you need to be able to access member variables from and get
callbacks to another object than the root node of a ccb-file. To do
this you will need to pass an owner to the CCBReader.
as explained in Connecting with cocos2d-x.
Owner var provides you with more flexibility by allowing you to connect to a variable other than the root node. You can glue it to any variable of your choosing.
The error you are getting is most likely caused by providing a name that is not available (the variable doesn't exist). Note that setting the property to Doc root var or Owner var and leaving the field empty will cause this error.
When linking member variables the Doc root var will add a member in the root node's controller object. You could access it via MainScene.myVar assuming that you JS Controller is MainScene. This is defined by your scene root layer JS Controller property.
Alternatively, you can do the same thing with a custom object that is not directly tied to the scene via the JS Controller connection. To achieve this, you would use the Owner var attribute.
Don't Assign is the default and doesn't do anything.
In essence, these features allows you to easily reference those CCB objects from your code.
Experimenting with the CocosBuilder JS Example Games may be of help. The documentation on how to connect with cocos2d-x might also be useful to you if you didn't read it yet.

How can I save a global variable value after dynamically loading a reference?

I have a Access 2003 database that will dynamically load MDB databases as a library reference. The reason for this is this database is a menu front-end for 60+ application databases. Rather than deal with permanently referencing all these databases, the menu front-end will dynamically reference what is needed when the user makes a selection. I was working on moving this database to Access 2010 and creating a custom ribbon. I started using the technique from here to capture the ribbon object in a global variable when the ribbon loads. I then ran into the problem where I could verify the code was running and the global variable was correctly being assigned the ribbon reference but after the database would run through it's startup routine, that global variable would get reset to Nothing.
To verify what was going on, I created a simple database for testing. In this database, I had a module with a global variable:
Public obj as Object
I then had a function like this:
Public Function SetObj()
Set obj = Application
Debug.Print "IsNothing=" & (obj Is Nothing)
References.AddFromFile "Test.mdb"
Debug.Print "IsNothing=" & (obj Is Nothing)
End Function
Obviously, in my code, "Test.mdb" refers to an actual file. If I run this code, Debug.Print gives me "IsNothing=False" for both instances, but after the function finishes and if I wait a couple seconds, Debug.Print will give me "IsNothing=True". If I comment out References.AddFromFile, Debug.Print gives me "IsNothing=False" no matter how long I wait.
It makes sense to me that since Access has to re-compile the VBA code after loading the library that all global variables are reset. I've experimented with moving the global variable into a class, but since I then need a global variable for the class, the class variable then gets reset instead. I tried using a local variable in the function to save the value of the global variable, but it looks like Access waits a couple seconds after the code is finished running to do the re-compile, so that doesn't work either. Does anyone have any other ideas to accomplish this?
I don't really know if this will solve the problem for this kind of reference, but in general, I don't use public variables for this kind of thing, but instead use a STATIC variable inside your function. It would be something like this:
Public Function SetObj() As Object
Static obj As Object
If (obj Is Nothing) Then
Set obj = Application
End If
Set SetObj = obj
End Function
Then you'd just use SetObj as an object for using your application. In a production app, you'd need tear-down code, too, but I've omitted that here.
I doubt this helps, but your code struck me as rather inefficient and incomplete.
I figured out a solution to my problem, and thanks #David-W-Fenton, as your answer gave me the idea. I use your approach in a library database for caching frequently-accessed values that are stored in a table but don't change after the initial startup. Those values aren't lost every time the references change, and that's when the light bulb lit up.
The solution is to put the global variable in a library database. Access looks to be only resetting global variables in the database that the reference is being loaded into - which makes sense after thinking about it. So since the library database isn't the one being re-compiled, it doesn't get it's global (or private or static) variables reset.
What I ended up doing was creating a new module in an existing library database. It has a private variable and two methods - one to set the variable, one to retrieve the variable value. In my menu front-end database, when the ribbon loads and calls my callback function, rather than saving the ribbon object in the front-end database, I pass it to this module for saving. I now no longer lose that ribbon reference whenever new databases are added to the library references on the fly.