Getting Window function to assign variable locally [duplicate] - javascript

This question already exists:
Why isn't my future value available now? [duplicate]
Closed 6 years ago.
I am trying to get my Angular2 service to use the LinkedIN javascript SDK that is loaded by the script linkedin provides. the functionality works for getting the data and returning it but I can't set the local function variable to the data I got back from linkeidn
export class LinkedInAuthService {
constructor(
) {
}
linkedInAuthorization() {
window['IN'].User.authorize();
window['IN'].Event.on(window['IN'], 'auth', this.getLinkedInUserInfo);
}
getLinkedInUserInfo() {
let linkedinInfo:any;
window['IN']
.API
.Raw()
.url("/people/~:(firstName,lastName,emailAddress,industry,specialties,positions)?format=json")
.result(function(data:any){
console.log(data) //logs data correctly
linkedinInfo = data
});
console.log(linkedinInfo) // undefined
}
AuthLinkedInUserforGlx() {
console.log(localStorage.getItem('linkedinInfo'))
}
}
I think the problem is when I set linkedinInfo = data it is not setting it locally, just not sure how to make it local

This worked for me
export class LinkedInService {
IN = window['IN'];
userProfile: Object;
constructor() {
this.userProfile = JSON.parse(localStorage.getItem('profile'))
this.IN.Event.on(this.IN, 'auth', this.getLinkedInUserInfo);
console.log('end of constructor')
}
linkedInAuthorization(){
this.IN.User.authorize();
console.log('end of linkedInAuthorization service')
}
getLinkedInUserInfo() {
this.IN.API.Raw()
.url("/people/~:(firstName,lastName,emailAddress,industry,specialties,positions)?format=json")
.result((data:any) => {
localStorage.setItem('profile', JSON.stringify(data));
this.userProfile = data;
});
console.log('end of getLinkedInUserInfo service');
this.AuthLinkedInOnGlx
}
AuthLinkedInOnGlx (){
}
}

Related

issue with this when two classes in one function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
I have two classes in a function and for some reason in the second function this is not being recognised correctly.
The classes are Emitter and Receiver.
I am trying to figure out why this is not being picked up correctly here. The log is included in the code below:
const chat = (messages) => {
class Emitter {
constructor(messages = []) {
this.messages = messages;
this.event = () => {};
}
setEvent(fn) {
this.event = fn;
}
trigger() {
this.messages.forEach(message => this.event(message));
}
}
class Receiver {
constructor() {
this.messages = [];
// this prints correctly here
---> Receiver { messages: [] }
console.log('this ===> ', this)
}
ping(message) {
console.log('this ===>', this)
// this here prints the following
this ===> Emitter {
messages: [ 'Hi', 'Hola', 'Bonjour', 'Hi' ],
event: [Function: ping] }
this.messages.push(message);
}
}
const myReceiver = new Receiver();
const myEmitter = new Emitter(messages);
myEmitter.setEvent(myReceiver.ping);
myEmitter.trigger();
return myReceiver.messages;
};
The this depends on the scope where it is called but not the scope it is defined.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
In the call myEmitter.setEvent(myReceiver.ping), only the function ping is passed to the myEmitter, not its scope myReciever. In case if you would like to pass myRevciever scope you can bind it the function call.
myEmitter.setEvent(myReceiver.ping.bind(myReceiver));

VueJS returns undefined in created function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
i have started working on a small project using VueJs, i've made a get request using Axios library which returns some data as expected, but I cannot call loadUsers function using this inside mounted
this is my code:
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then(function(data){
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
as you can see also i've used self variable to call my loadUsers() function, but i'm still getting
this is undefined error
You're referencing this.users within the callback to axios.get().then() in loadUsers(). Due to you're using a standard function and not an arrow function, this is not referring to the Vue instance, i.e. the scope for this is now incorrect. Either use an arrow function or change the reference:
// Do this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then((data) => { // Using an arrow function.
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
// Or this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
let self=this; // Adding "self"
axios.get('/Thirdparty/loadUsers').then(function(data){
self.users = data.data; // Referencing "self" instead of "this".
});
}
},
created(){
let self=this
self.loadUsers();
}
}

this.setData is not a function in react [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I am getting this weird issue in facebook login where I get the response but after getting the response, I am not able to dispatch actions.
Therefore, I wrote a function to do this but I am getting this.setData is not a function.
testAPI() {
window.FB.api('/me' ,function(response) {
console.log("testAPI",response);
if(response){
userProfile = {
access_token:accessToken,
id:response.id,
name:response.name,
provider: "Facebook",
};
console.log("userProfile",userProfile);
this.setData(userProfile);
}
console.log('[FacebookLoginButton] Successful login for: ', response);
});
}
setData = userProfile => {
this.setState(
{
userData: userProfile
},
() => {
console.log("inside setData");
if (userProfile !== undefined) {
console.log("inside callback", userProfile);
this.props.loginUser(this.state.userData);
}
}
);
};
This will help ( https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56 ) [ You need to bind function in order to set context of this ]
You have to use arrow function, or bind function to set correct context of this.
window.FB.api('/me', response => {
// function body
}

Signaling OpenTok and React

Has anyone implemented sending and receiving signals with opentok-react https://github.com/aiham/opentok-react? I can't find even a simple example on how to do it in React using opentok-react.
Thanks for using opentok-react. Unfortunately an easy way to do signaling hasn't yet been added to opentok-react so the following process is a bit convoluted.
To do signaling you will need to get access to the Session object and call the signal method on it as you normally would (See https://tokbox.com/developer/sdks/js/reference/Session.html#signal).
If you used the OTSession component you can access the Session object by getting a reference to the OTSession element (See https://reactjs.org/docs/refs-and-the-dom.html).
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.otSession = React.createRef();
}
render() {
return <OTSession ref={this.otSession} />;
}
}
and using its sessionHelper property to call the signal method:
this.otSession.current.sessionHelper.session.signal(...);
If you want to specify a particular target connection for the recipient then you need to get it from the underlying Publisher or Subscriber object's stream property. First get a reference to the OTPublisher or OTSubscriber element :
<OTPublisher ref={this.otPublisher} />
// or
<OTSubscriber ref={this.otSubscriber} />
Then get access to the Connection object:
this.otPublisher.current.getPublisher().stream.connection
// or
this.otSubscriber.current.getSubscriber().stream.connection
I have not tested this but once you have access to the Session and Connection objects then you can use the full signaling capabilities of the OpenTok JS SDK.
I Created a npm package 'opentok-rvc' with reference to opentok-react.
Here i created a listener to watch signaling and if any signal gets i send the signal to another event
// signal message listener inside npm package
session.on('signal:msg', function signalCallback(event) {
console.log(event);
onSignalRecieve(event);
});
Inside your component, please do the following
// to send the opentok signal
// here param data can be object for eg:
// data = { type: 'START_VIDEO_CALL', data: 'By Alex' }
onSignalSend = (data) => {
if (this.otSession.current !== null) {
this.otSession.current.sessionHelper.session.signal({
type: 'msg',
data: data
}, function signalCallback(error) {
if (error) {
console.log('onSignalSend Error', error)
} else {
console.log('onSignalSend Success', data)
}
})
}
}
// to receive the opentok signal
onSignalReceive = (signal) => {
console.log('onSignalReceive => ', JSON.parse(signal.data));
// based on signal data type you can do use switch or conditional statements
}
<OTSession
ref={this.otSession}
apiKey={apiKey}
sessionId={sessionId}
token={token}
onError={this.onSessionError}
eventHandlers={this.sessionEventHandlers}
onSignalRecieve={this.onSignalReceive}
getDevices={this.setDevices}
onMediaDevices={this.onMediaDevices}
checkScreenSharing={this.checkScreenSharing}>
<OTPublisher properties/>
<OTStreams>
<OTSubscriber properties/>
</OTStreams>
Here's a way to do this using functional component syntax.
import React, { useRef } from 'react';
import { OTSession, preloadScript } from 'opentok-react';
function MyComponent() {
const sessionRef = useRef();
const sendSignal = () => {
sessionRef.current.sessionHelper.session.signal(
{
type: 'TheSignalType',
data: 'TheData',
},
function (error) {
if (error) {
console.log('signal error: ' + error.message);
} else {
console.log('signal sent');
}
}
);
};
return (
<OTSession ref={sessionRef} apiKey={apiKey} sessionId={sessionId} token={token} eventHandlers={eventHandlers}>
// rest of your tokbox code here
<Button onClick={sendSignal}>Send Signal</Button>
</OTSession>
);
}
export default preloadScript(MyComponent);
In addition to #aiham answer, You can access the Opentok session Object getting the ref from the OTSession element and then send signals like below
otSession.current.sessionHelper.session.signal(
{
type: "msg",
data: text,
},
function(err, data) {
if (err) {
console.log(err.message);
} else {
console.log(data)
}
}
);
And signals can be received by adding a listener as follows;
otSession.current.sessionHelper.session.on("signal", (event) => {
console.log("i got", event);
});

Meteor JS - Client Collection seems to be empty

Its been a long time since I used Meteor or dabbled in the UI world for that matter, so forgive me if this is poor question.
api/main.js:
export const Nodes = new Meteor.Collection("nodes");
export const Links = new Meteor.Collection("links");
server/main.js
import { Links, Nodes } from '../api/main.js';
Meteor.startup(() => {
// code to run on server at startup
}
Meteor.methods({
traverseDocument: function traverseDocument(documentKey) {
// ... do stuff ...
Links.insert( data.links );
Nodes.insert( data.nodes );
return data;
}
}
client/main.js
import { Links, Nodes } from '../api/main.js';
import './main.html';
Meteor.startup(function () {
// Fetch data via a call
Meteor.call("traverseDocument", 'NTD000000228506', function (error, results) {});
});
Template.viz.rendered = function () {
console.log(Nodes.find()); // <-- LocalConnection.Cursor()
console.log(Nodes.find().fetch()); // <-- This is empty []
console.log(Nodes._collection._docs._map); // <-- This returns Object{}
}
I've tried:
1. Publish/Subscribe
2. I tried a helper function
3. I Have moved the Meteor.Call() into the client startup function
So this now seems to be closer to working.
The original question changes now to - Why does the find().fetch() return an empty array ?
Maybe I should post a new question and mark this one as fixed ?
You can save value of results from callback to session variable or reactive variable and then retrieve later.
import { Links, Nodes } from '../api/main.js';
import './main.html';
Template.viz.rendered = function () {
Meteor.call("traverseDocument", 'VALUE001', function (error, results) {
if(error) {
// handle error
}
else {
Session.set('result',results); // save result in session or reactive variable
}
console.log(Nodes); // <-- This works, has data
});
if(Session.get('result') {
console.log(Session.get('result')); // <-- Retrieve value from session or reactive var
}
}

Categories