Is it possible to return a Node object from a file to another?
ex:
file_1
myObject = function(x){
this.x = x
this.change = function(){
return myObject("new_value");
}
}
module.exports = myObject;
file_2
F1 = require('file_2');
f1 = new F1("some_value");
new = f1.change();
On my code, new now has "undefined". Is there a way to return the new object?
file_1 should be:
myObject = function(x){
this.x = x
this.change = function(){
return myObject("new_value");
}
}
module.exports = myObject;
Related
I have some class MyObject
MyObject * m_instance;
extern "C"
{
void createNew()
{
m_instance = new MyObject ("one", "two");
}
const char * getCharOne()
{
std::cout<< "one" <<m_instance->getFirstString().c_str()<<std::endl;
return m_instance->m_instance->getFirstString().c_str();
}
}
//example.js
var ffi = require('ffi');
var libm = ffi.Library('libExample', {
'createNew': ["void",[]],
'getCharOne' : ['string',[]],
});
libm.createNew();
var o = libm.getCharOne();
console.log(o);
i get the print inside the getCharOne function, but not from the console log.
Any help will be greatly appreciated
I have create a group in phaserjs
this.fruitsOutline = this.game.add.group();
After that I have added few sprites in it. Everything is working correctly. Now if want to access this.fruitsOutline, from inside of a onDragStart event handler, it is giving undefined
var GameState = {
init:function(){
this.physics.startSystem(Phaser.Physics.ARCADE);
},
create: function () {
var innerImgPos = {x:150,y:200};
var outlineImgPos = {x:460,y:200};
var FIXED_DISTANCE_Y = 150;
var gameData = [
//...some data
];
this.background = this.game.add.sprite(0, 0, 'background');
this.overlapHappen = false;
this.startPos = {x:150,y:197};
this.fruitsOutline = this.game.add.group();
this.fruitsInner = this.game.add.group();
for(var i=0; i<gameData.length; i++){
fruitOuter = this.fruitsOutline.create(outlineImgPos.x,((outlineImgPos.y+25)*i)+FIXED_DISTANCE_Y,gameData[i].fruit_outline.img);
fruitOuter.name = gameData[i].fruitName;
fruitOuter.anchor.setTo(.5);
fruitOuter.customParams = {myName:gameData[i].fruit_outline.name};
this.game.physics.arcade.enable(fruitOuter);
fruitOuter.body.setSize(100,100,50,50);
fruitInner = this.fruitsInner.create(innerImgPos.x,((innerImgPos.y+25)*i)+FIXED_DISTANCE_Y,gameData[i].fruit_inner.img);
fruitInner.name = gameData[i].fruitName;
fruitInner.anchor.setTo(0.5);
fruitInner.inputEnabled = true;
fruitInner.input.enableDrag();
fruitInner.input.pixelPerfectOver = true;
fruitInner.originalPos = {x:fruitInner.position.x,y:fruitInner.position.y};
this.game.physics.arcade.enable(fruitInner);
fruitInner.body.setSize(100,100,50,50);
fruitInner.customParams = {myName:gameData[i].fruit_inner.name,targetKey:fruitOuter,targetImg:gameData[i].fruit_outline.name};
fruitInner.events.onDragStart.add(this.onDragStart);
fruitInner.events.onDragStop.add(this.onDragStop,this);
}
},
update: function () {
},
onDragStart:function(sprite,pointer){
console.log(this.fruitsInner) //this gives undefined I expect an array
},
onDragStop:function(sprite,pointer){
var endSprite = sprite.customParams.targetKey;
console.log(endSprite);
this.stopDrag(sprite,endSprite)
},
stopDrag:function(currentSprite,endSprite){
var currentSpriteRight = currentSprite.position.x + (currentSprite.width / 2);
if (!this.game.physics.arcade.overlap(currentSprite, endSprite, function() {
var currentSpriteTarget = currentSprite.customParams.targetImg;
var endSpriteName = endSprite.customParams.myName;
console.log(currentSpriteTarget,endSpriteName);
if(currentSpriteTarget === endSpriteName){
currentSprite.input.draggable = false;
currentSprite.position.copyFrom(endSprite.position);
currentSprite.anchor.setTo(endSprite.anchor.x, endSprite.anchor.y);
}
console.log(currentSprite.width);
})) {
//currentSprite.position.copyFrom(currentSprite.originalPosition);
currentSprite.position.x = currentSprite.originalPos.x;
currentSprite.position.y = currentSprite.originalPos.y;
}
},
render:function(){
game.debug.body(this.fruitsInner);
//game.debug.body(this.orange_outline);
}
}
You're missing the context when adding the drag callback.
Try that (adding this as the second argument):
fruitInner.events.onDragStart.add(this.onDragStart, this);
Oh, and inside the callback (or anywhere in the state) this.fruitsInner will be an instance of Phaser.Group, not an array like that comment says. The array you're looking for is probably this.fruitsInner.children.
Since from co#4.0+ we can use below statement
var fn = co.wrap(fn*)
to convert a generator into a regular function that returns a Promise.
Then I face a problem
a.js
var F = function *(a,b,c){
this.a = yield this.getA(a);
this.b = yield this.getB(b);
this.c = yield this.getC(c);
}
F.prototype.getA = function * (a){
//........
}
F.prototype.getB = function * (b){
//........
}
F.prototype.getC = function * (c){
//........
}
exports.F = F;
how to create a instance in b.js by co .
#Bergi said it`s a bad practice
then I want to ask anthor question
function* F(){
yield this.x = 2;
yield this.y = 3;
}
var obj = {};
var f = F.bind(obj)();
f.next();
f.next();
f.next();
console.log(obj);
// { x: 2, y: 3 }
is it a bad practice ?
I am making an application using the express framework of node.js. I have to use OOP features like inheritance in my application.
I created a simple class in routes/model folder.
exports.Rectangle = function(x,y)
{
this.x = x;
this.y = y;
}
Rectangle.prototype.getArea = function()
{
return (this.x * this.y);
}
Rectangle.prototype.toString = function()
{
var tmp = "Rectangle " + this.x + " : " + this.y;
return tmp;
}
My routes/index.js is like this:
exports.index = function(req, res){
var RectangleClass = require('./model/Rectangle.js');
var rect1 = new RectangleClass.Rectangle(4,6);
console.log(rect1.getArea());
console.log("Rect: " + rect1);
res.send("hello");
};
When I run the app I get the error: 500 ReferenceError: Rectangle is not defined
The error is shown at the Rectangle.prototype.getArea = function() line in routes/model/Rectangle.js
However, if I copy paste the Rectangle class structure in my index.js file, then it is all working. But I have many classes and I do not want to define them all in one file. How can I reference objects defined in other files?
This is the problem in your initial setup:
exports.Rectangle = function(x, y) {
...
}
Rectangle.prototype.getArea = ...
exports.Rectangle doesn't magically create a variable called Rectangle in the current module, hence the undefined error when you try to use Rectangle.prototype.
There are a couple of solutions:
// one solution
var Rectangle = exports.Rectangle = function(x, y) { ... }
Rectangle.prototype.getArea = ...
// another solution
var Rectangle = function(x, y) { ... }
Rectangle.prototype.getArea = ...
exports = Rectangle;
// yet another solution
exports.Rectangle = function(x, y) { ... }
exports.Rectangle.prototype.getArea = ...
Or the one you found out yourself, although creating such a factory function isn't really necessary :)
This suddenly occurred to me. I used a getter method to create and return a Rectangle object. The following changes were made in Rectangle.js.
exports.getRectangle = function(x,y)
{
var r = new Rectangle(x,y);
return r;
}
Rectangle = function(x,y)
{
this.x = x;
this.y = y;
}
The other methods were left unchanged.
In my index.js file, instead of
var r = new RectangleClass.Rectangle(6,4);
I used
var r = RectangleClass.getRectangle(6,4);
I have a method that calls stored procedure and returns the data after executing DataReader.
I am trying to test the method using mock. I am not sure how to return value?
Anyone did this? Appreciate your responses.
Here is my code:
// Call the StoredProcedure
public List<string> GetCompletedBatchList(int fileId)
{
List<string> completedBatches = new List<string>();
StoredProcedure sp = new StoredProcedure("GetDistributedBatches", this.dataProvider);
sp.Command.AddParameter("FileID", fileId, DbType.Int32, ParameterDirection.Input);
sp.Command.AddParameter("Result", null, DbType.Int32, ParameterDirection.InputOutput);
using (var rdr = sp.ExecuteReader())
{
while (rdr != null && rdr.Read())
{
if (rdr[0] != null)
{
completedBatches.Add(rdr[0].ToString());
}
}
}
return completedBatches;
}
Here is the Test Method:
[Test]
public void Can_get_completedBatches()
{
var file = new File() { FileID = 1, DepositDate = DateTime.Now };
repo.Add<File>(file);
CompletedBatches completedBatches = new CompletedBatches(provider.Object);
//Here I am not sure how to Return
provider.Setup(**x => x.ExecuteReader(It.IsAny<QueryCommand>())).Returns** =>
{
cmd.OutputValues.Add(0);
});
var completedBatchesList = completedBatches.GetCompletedBatchList(file.FileID);
Assert.AreEqual(0, completedBatchesList.Count());
}
If you want to create a DataReader of a certain shape and size then I suggest you look at DataTable.CreateDataReader DataTable.CreateDataReader. You can then setup the ExecuteReader in your example to return this datareader.
The following link helped me...
How to mock an SqlDataReader using Moq - Update
I used MockDbDataReader method to mock the data
[Test]
public void Can_get_completedBatches_return_single_batch()
{
var date = DateTime.Now;
var file = new File() { FileID = 202, DepositDate = DateTime.Now };
var batch1 = new Batch() { FileID = 202, BatchID = 1767, LockboxNumber = "1", IsLocked = true, LockedBy = "testUser" };
var transaction1 = new Transaction() { BatchID = 1767, TransactionID = 63423, CheckAmount = 100.0 };
var distribution1 = new Distribution() { TransactionID = 63423, InvoiceNumber = "001", Amount = 100.0, DateCreated = date, DateModified = date, TransType = 2 };
repo.Add<File>(file);
repo.Add<Batch>(batch1);
repo.Add<Transaction>(transaction1);
repo.Add<Distribution>(distribution1);
CompletedBatches completedBatches = new CompletedBatches(provider.Object);
provider.Setup(x => x.ExecuteReader(It.IsAny<QueryCommand>())).Returns(MockDbDataReader());
var completedBatchesList = completedBatches.GetCompletedBatchList(202);
Assert.AreEqual(1, completedBatchesList.Count());
}
// You should pass here a list of test items, their data
// will be returned by IDataReader
private DbDataReader MockDbDataReader(List<TestData> ojectsToEmulate)
{
var moq = new Mock<DbDataReader>();
// This var stores current position in 'ojectsToEmulate' list
int count = -1;
moq.Setup(x => x.Read())
// Return 'True' while list still has an item
.Returns(() => count < ojectsToEmulate.Count - 1)
// Go to next position
.Callback(() => count++);
moq.Setup(x => x["BatchID"])
// Again, use lazy initialization via lambda expression
.Returns(() => ojectsToEmulate[count].ValidChar);
return moq.Object;
}