ObjPool allow you to recycle or allocate objects in a pool easily. When you need an instance of your object, the pool will return you one of them, or a new instance if it's empty.
npm install obj-pool
var ObjPool = require('obj-pool');
Add obj-pool.js to your HTML and ObjPool will be added to window
//window.ObjPool
if(ObjPool)console.log('Cool!');
//Creating the pool of MyEntity
var pool = new ObjPool(MyEntity);
//getting an instance of MyEntity
var entity = pool.alloc();
/* do something with entity */
//put back the entity instance in the pool
pool.free(entity);
If your object needs some params you can use {args:[]}
option as second param.
var audioPool = new ObjPool(Audio, {args: ['./assets/audio.mp3']});
Use `{amount: N}``
var pool = new ObjPool(MyEntity, {amount: 100});
You can use some functions to init
and reset
your objects.
function MyEntity(){
}
MyEntity.prototype.constructor = MyEntity;
MyEntity.prototype.init = function(){
//Do something to initialize me when I go out of my pool
}
MyEntity.prototype.reset = function(){
//Do something with me when I return to my pool
}
var pool = new ObjPool(MyEntity);
var entity = pool.alloc(); //This fire MyEntity.init();
pool.free(entity); //This fire MyEntity.reset();
If you need other function's names to init
and reset
, you can change the value of objInit
and objReset
:
var pool = new ObjPool(MyEntity);
pool.objInit = 'initialize'; //Looks for MyEntity.initialize() instead of MyEntity.init();
pool.objReset = 'resetMe'; //Looks for MyEntity.resetMe() instead of MyEntity.reset();
Pass the objects to create, and the options (Optional) with the amount and object arguments. `{args: [arg1, arg2, ...], amount: 100}'
Return an object to use it and remove it from the pool.
Put back an object into the pool to reuse it.
Create a N numbers of the object and add to the objects list.
Erase all the object from the objects list.
Return the objects list length