EDIT: Solved by renaming the this.powerOn declaration in all of the class constructors.
I have a function that pulls data from a database and stores it in the appropriate array(s). I have another function that iterates through said array(s) and instantiates a new instance of a class based on a targeted property & these instances are stored in a separate array. I am having trouble triggering methods of said instances that, as far as I can tell, should be apart of them.
Currently this is how I am attempting to handle this:
const SourceModel = require('../models/Source');
const DisplayModel = require('../models/Display');
const Roku = require('../_data/sdk/Roku');
const Sony = require('../_data/sdk/Sony');
const driversArray = [];
const liveDriverInstances = [];
// Returns new class instance based on DriverModel
class instantiatedDriverClass {
constructor(DriverModel, DriverIPAddress, DriverPort) {
let driverClasses = {
Roku,
Sony
};
return new driverClasses[DriverModel](DriverIPAddress, DriverPort)
}
}
// Pull sources, displays, ..., from DB
const getDevicesFromDB = async () => {
sourcesArray = await SourceModel.find();
displaysArray = await DisplayModel.find();
};
// Create new array from sources, displays, ..., arrays & iterate to instantiate matching driver class
const loadDeviceDriversToRuntime = async () => {
await getDevicesFromDB();
sourcesArray.forEach((source) => driversArray.push(source));
displaysArray.forEach((display) => driversArray.push(display));
driversArray.forEach((driver) => {
liveDriverInstances.push(new instantiatedDriverClass(driver.driver.driverModel, driver.ipaddress, driver.port));
});
};
// Executed by server after connection to DB is established
const importDrivers = () => {
loadDeviceDriversToRuntime();
}
module.exports = importDrivers, driversArray;
The two classes (so far) that I am trying to execute methods on are Roku and Sony. Roku extends MediaPlayer and Sony extends Display. MediaPlayer and Display extends Commands. Code for Roku class:
const MediaPlayer = require('./MediaPlayer');
class Roku extends MediaPlayer {
constructor(ipaddress, port, powerOnDelay, powerOffDelay) {
super();
let url = `https://${ipaddress}:${port}`
this.powerOn = `${url}/powerOn`;
this.powerOff = `${url}/powerOff`;
this.up = `${url}/up;`
this.down = `${url}/down`;
this.left = `${url}/left`;
this.right = `${url}/right`;
this.enter = `${url}/enter`;
this.select = `${url}/select`;
this.back = `${url}/back`;
this.backspace = `${url}/backspace`;
this.exit = `${url}/exit`;
this.guide = `${url}/guide`;
this.menu = `${url}/menu`;
}
powerOn() {
super.powerOn(this.powerOn);
}
powerOff() {
super.powerOff(this.powerOff);
}
}
module.exports = Roku;
Code for MediaPlayer class:
const Commands = require('./Commands');
class MediaPlayer extends Commands {
constructor(powerOn, powerOff, up, down, left, right, enter, select, back, backspace, exit, guide, menu) {
super();
this.powerOn = powerOn;
this.powerOff = powerOff;
this.up = up;
this.down = down;
this.left = left;
this.right = right;
this.enter = enter;
this.select = select;
this.back = back;
this.backspace = backspace;
this.exit = exit;
this.guide = guide;
this.menu = menu;
}
powerOn() {
super.powerOn(this.powerOn);
}
powerOff() {
super.powerOff(this.powerOff);
}
}
module.exports = MediaPlayer;
Code for Commands class:
class Commands {
constructor(command) {
this.command = command;
}
powerOn(command) {
console.log("Something")
}
powerOff(command) {
console.log("Something")
}
up(command) {
console.log("Something")
}
down(command) {
console.log("Something")
}
left(command) {
console.log("Something")
}
right(command) {
console.log("Something")
}
enter(command) {
console.log("Something")
}
play(command) {
console.log("Something")
}
pause(command) {
console.log("Something")
}
select(command) {
console.log("Something")
}
guide(command) {
console.log("Something")
}
menu(command) {
console.log("Something")
}
back(command) {
console.log("Something")
}
delete(command) {
console.log("Something")
}
speed1(command) {
console.log("Something")
}
speed2(command) {
console.log("Something")
}
speed3(command) {
console.log("Something")
}
HDMI1(command) {
console.log("Something")
}
HDMI2(command) {
console.log("Something")
}
HDMI3(command) {
console.log("Something")
}
}
module.exports = Commands;
As far as I understand, the methods powerOn() and powerOff() should be accessible when an instance of Roku or Sony is created. If, however, I try to do something like liveDriverInstances[0].powerOn() I get an error liveDriverInstances[0].powerOn is not a function. When I run console.log(liveDriverInstances[0]) I get this response:
Roku {
command: undefined,
powerOn: 'https://192.168.1.205:8060/powerOn',
powerOff: 'https://192.168.1.205:8060/powerOff',
up: 'https://192.168.1.205:8060/up;',
down: 'https://192.168.1.205:8060/down',
left: 'https://192.168.1.205:8060/left',
right: 'https://192.168.1.205:8060/right',
enter: 'https://192.168.1.205:8060/enter',
select: 'https://192.168.1.205:8060/select',
back: 'https://192.168.1.205:8060/back',
backspace: 'https://192.168.1.205:8060/backspace',
exit: 'https://192.168.1.205:8060/exit',
guide: 'https://192.168.1.205:8060/guide',
menu: 'https://192.168.1.205:8060/menu'
}
So the data is being passed down from the Roku instance inheriting from MediaPlayer inheriting from Commands, but I don't have the methods. Looks like it is just getting the constructor method, but nothing more. Have I defined something incorrectly here?
On the constructor of Roku class. you are initializing the powerOn as a String . This will replace the function powerOn() declared.
constructor(ipaddress, port, powerOnDelay, powerOffDelay) {
...
this.powerOn = `${url}/powerOn`;
...
}
You can make this work by renaming the url fields
constructor(ipaddress, port, powerOnDelay, powerOffDelay) {
...
this.powerOnUrl = `${url}/powerOn`;
...
}
powerOn() {
super.powerOn(this.powerOnUrl);
}
Related
Hi i have parent module like this.
// usermgmt.js
var usermgmt = function () {};
usermgmt.prototype.test = function () {
return "test";
};
usermgmt.private = function () {
return "private";
};
module.exports = new usermgmt();
and a Child prototype class like this.
// authentication.js
var usermgmt = require('./usermgmt');
var authentication = function () {};
authentication.prototype.callParent = function () {
usermgmt.private();
};
module.exports = new authentication();
How i implement inheritance? I searched by google but no solution works for me.
Here's a typical way to export a base class and then import it and inherit from it using the more modern syntax:
// a.js
class A {
constructor() {
}
testA() {
return "testA";
}
}
module.exports = A;
Then, in a separate file:
// b.js
const A = require('./a.js');
class B extends A {
constructor() {
super();
}
testB() {
return "testB";
}
}
let x = new B();
x.testA(); // "testA" - this is inherited obviously
x.testB(); // "testB"
As #jfriend00 said, I write these functions with class keyword which is a syntactic sugar for your code!
usermgmt.js
// usermgmt.js
class usermgmt {
constructor() {
}
test() {
return "test";
}
private() {
return "private";
}
}
module.exports = usermgmt;
Write authentication like this.
authentication.js
// authentication.js
var Usermgmt = require('./usermgmt.js');
class authentication extends Usermgmt {
constructor() {
super();
}
callParent() {
console.log(this.private());
}
authFunction() {
console.log(':: authFunction ::');
this.callParent();
}
}
module.exports = authentication;
And usage for authentication will be:
var Authentication = require('./authentication.js');
let auth = new Authentication();
auth.callParent();
auth.authFunction();
console.log(auth.test());
1) Use class and extends syntax which is easier.
2) Return Class and not its instance
Trying to save and reuse a query- clone();
I have already tried query.clone(), clone(query), statics.clone(query), graphPredicate.clone(query)
reference: http://tinkerpop.apache.org/docs/current/recipes/#traversal-component-reuse
const { Graph } = gremlin.structure;
const { P: graphPredicate, statics } = gremlin.process;
const { _ } = gremlin.process.statics;
const g = graph.traversal().withRemote(gremlinConnection);
const query = statics.hasLabel(‘Movie’).hasId(gt(‘C’))
const count = g.V().flatMap(query.clone()).count().next()```
`Exception: TypeError: Cannot read property 'clone' of undefined`
There's no clone() in javascript. But you can easily create one:
function clone(traversal) {
return new gremlin.process.GraphTraversal(
traversal.graph,
traversal.traversalStrategies,
new gremlin.process.Bytecode(traversal.bytecode)
)
}
you can also add it to the traversal itself: http://tinkerpop.apache.org/docs/current/reference/#gremlin-javascript-dsl
class MyTraversal extends gremlin.process.GraphTraversal {
constructor(graph, traversalStrategies, bytecode) {
super(graph, traversalStrategies, bytecode)
}
clone() {
return new MyTraversal(
this.graph,
this.traversalStrategies,
new gremlin.process.Bytecode(this.bytecode)
)
}
}
class MyTraversalSource extends gremlin.process.GraphTraversalSource {
constructor(graph, strategies, bytecode) {
super(graph, strategies, bytecode, MyTraversalSource, MyTraversal)
}
}
const g = traversal(MyTraversalSource).withRemote(dc)
I used to implement singleton this way:
class MySomething {
constructor(props) {}
}
let myInstance = null;
module.exports = (props) => {
//first time call
if(props) {
myInstance = new MySomething (props);
return myInstance;
} else {
return myInstance;
}
this assumes that at app.js (entry file) I will call first:
require('./MySomething')(props)
then everywhere in the project I use:
const instanceOfSomething = require('./MySomething')();
I discovered that every time I got a new instance!
What's wrong in my code?
I tried also this way:
class MySomething {...}
const mySomething = (function() {
let myInstance = null;
return {
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
})();
module.exports = mySomething;
and I got the some problem when importing this module from different files, anyone can explain to me?
every require of file create new instance of mySomething
UPDATE
I tried this example now:
class MySomething {...}
const mySomething = {
myInstance: null,
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
};
module.exports = mySomething;
The same problem happened, maybe it is related to my project structure, I will explain it here:
the code below belongs to module "facts"
facts folder contains a folder named "dao" this folder contains MySomething.js (the singleton)
in the facts/index.js I have:
const Localstorage = require('./dao/MySomething');
exports.init = (path) => {
Localstorage.init(path)
}
exports.Localstorage = Localstorage;
Now in a folder named "core" which contains the "facts" folder I re-exported the Localstorage again in "index.js" like this:
const facstModule = require('./facts');
exports.Localstorage = facstModule.Localstorage;
Then in "schedule" folder which contains "Runtime.js" within I write:
const { Localstorage } = require('../core');
setTimeout(() => {
const localstorageIns = Localstorage.getInstance(); //this is always null!
}, 5000)
In app.js file (entry point) I did:
const facts = require('./src/facts');
facts.init(__dirname);
Normally instance will be created before the timeout execute the callaback,
But I noticed that there two instance of Localstorage which is singleton
the cleanest way to do a singleton is
class MyClass () { ... }
module.exports = new MyClass()
if you need a singleton that gets instantiated once, I would do:
class MyClass () { ... }
let myClass
const MyClassSingleton = (...args) => {
if (myClass) {
return myClass
}
myClass = new MyClass(...args)
return myClass
}
module.exports = MyClassSingleton
Every require of file create new instance of mySomething because every time you return new object with init method and getInstance method.
If you need singleton you need do like this:
class MySomething {
constructor() {
if (!MySomething.instance) {
MySomething.instance = this;
}
}
getInstance: function() {
return MySomething.instance;
}
}
module.exports = MySomething;
class Singleton {
constructor() {
this.my_obj;
}
static makeObject() {
if (!this.my_obj) {
this.my_obj = new Singleton();
}
return this.my_obj;
}
add() {
return 1
}
}
// so to get the object we need to call the makeobject method
const obj = Singleton.makeObject()
console.log(obj.add());
I am working on a VR project which is has 2 user roles, a leader (who sets up and configures a VR session) and clients (who connect to this session).
I am using a Native module to perform a DOM overlay in which several buttons related to session configuration are displayed for the leader. I was wondering if it is possible to call a function within the React360 code directly from a Native Module (i.e. not as a callback as the event would originate from the Native Module)?
This could be a complete anti-pattern, I can't seem to see a way of doing it...
I actually got this working with the following:
In client.js I passed the context to the DOM overlay native module:
const r360 = new ReactInstance(bundle, parent, {
// Add custom options here
fullScreen: true,
cursorVisibility: "visible",
nativeModules: [
// Create an instance of the DOM overlay module and pass the context
ctx => new DashboardModule(ctx, domDashboardContainer)
],
...options,
});
In the dashboard native module :
const eventToOb = (event) => {
const eventOb = {};
for (let key in event) {
const val = event[key];
if (!(lodash.isFunction(val) || lodash.isObject(val))) {
eventOb[key] = val;
}
}
return eventOb;
};
....
constructor(ctx, overlayContainer) {
super('DashboardModule');
...
this._rnctx = ctx;
this._bridgeName = 'BrowserBridge';
}
onButtonClick() {
....
this._emit('nativeButtonClicked', event);
}
_emit(name, event) {
if (!this._rnctx) {
return;
}
const eventOb = eventToOb(event);
this._rnctx.callFunction(this._bridgeName, 'notifyEvent', [name, eventOb]);
}
...
and in my index.js
...
import BatchedBridge from 'react-native/Libraries/BatchedBridge/BatchedBridge';
import lodash from 'lodash';
class BrowserBridge {
constructor() {
this._subscribers = {};
}
subscribe(handler) {
const key = String(Math.random());
this._subscribers[key] = handler;
return () => {
delete this._subscribers[key];
};
}
notifyEvent(name, event) {
lodash.forEach(this._subscribers, handler => {
handler(name, event);
});
}
}
const browserBridge = new BrowserBridge();
BatchedBridge.registerCallableModule(BrowserBridge.name, browserBridge);
....
constructor(props) {
super(props);
this.onBrowserEvent = this.onBrowserEvent.bind(this);
...
}
componentWillMount() {
this.unsubscribe = browserBridge.subscribe(this.onBrowserEvent);
}
onBrowserEvent(name, event) {
// Do action on event here
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
delete this.unsubscribe;
}
}
If there is a better way of doing this please let me know.
I have a Websocket.JS that is defined as the following :
class Websocket extends Component {
constructor(props) {
super(props);
const url = Config.ws + Config.baseEndPoint + Config.pen;
const protocol = this.props.protocol;
const doesLogging = (this.props.doesLogging === "true");
this.state = {"url": url,
"protocol": protocol,
"socket": new WebSocket(url, protocol),
"doesLogging": doesLogging};
};
onOpen() {
}
onMessage(msg) {
}
onClose() {
}
render() {
return (
<div id="websocket"></div>
);
}
}
export default Websocket;
And use it in the app.js like this:
import Websocket from './services/websocket';
<Websocket handleMessage={(msg) => this.messageReceived(msg.data)} />
However, I want to use it just as a module without it being represented like an HTML element. Is there any possible I can do that ?
I do not think that interaction via websockets must be presented in your code by using any kind of the UI library. Therefore:
class YourWebsocket{
constructor(protocol, url, enableLogging) {
this.url = url;
this.protocol = protocol;
this.loggingEnabled = enableLogging;
this.socket = new WebSocket(url, protocol);
this.socket.onopen = (ev) => this.onOpen();
// Assign more handlers here
}
onOpen() {
}
onMessage(msg) {
}
onClose() {
}
send(data, callback)
{
var listener = (e) =>
{
var reply = e.data;
if(replyIsForOurRequest) //Here you should come up with the logic to decide if this is reply for your request
{
this.socket.removeEventListener("message", listener);
callback(reply);
}
};
this.socket.addEventListener("message", listener);
this.socket.send(data);
}
}
export default YourWebsocket;
And in your app.js somewhere in componentDidMount method:
import YourWebsocket from './services/YourWebsocket';
class App extends React.Component
{
componentDidMount()
{
this.webSocket = new YourWebsocket();
//...
}
}