How to call method in symbol without assigning to variable - ecmascript-6

The following works fine by assigning Symbol to sayHello.
var sayHello = Symbol('method');
const bar = {
[sayHello] () {
console.log('hello')
}
};
bar[sayHello]();
How to trigger the method inside Symbol if as follow
const bar3 = {
[Symbol('method')] () {
console.log('hello')
}
};

const sym = Object.getOwnPropertySymbols(bar3)[0];
bar3[sym]();
See Object.getOwnPropertySymbols documentation.

Related

How call C function in js with render SDL in canvas

I am trying to render in canvas the module that I built with SDL2, but I also need to call functions while the module is running and send data there, according to the examples I found it turns out so:
var Module = {
canvas: (function () {
var canvas = document.getElementById('canvas');
canvas.addEventListener('webglcontextlost', e => {
alert('WebGL context lost. You will need to reload the page.');
e.preventDefault();
}, false);
return canvas;
})(),
};
SSE.onmessage = msg => {
Module.onRuntimeInitialized = () => {
Module.ccall('set_num', null, ['number'], [msg]);
};
}
The function was called once, but I need to call it constantly in the event
make with
override CFLAGS += -std=c11\
-Os\
-sUSE_SDL_TTF=2\
-sUSE_SDL_IMAGE=2\
-sSDL2_IMAGE_FORMATS=["png"]\
-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']\
-sUSE_SDL=2\
-sWASM=1\
-sASSERTIONS\
--preload-file ./res
C
#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
void set_num(int num) { g_obj->num = num; }

JSON data into variable

EDIT: I solved that error, however, it only seems to print out just one instance. How can I make it put all the entries into that variable?
I'm a little bit too new to this, but I'm trying. Sorry if the question sounds stupid.
I've configured a JSON server and it works just fine. I can pull out the data successfully, however, the data I receive I'd like to go into a variable so that I can use it later on in another function. For this purpose, I created the variable dategraph. However, it doesn't seem to work good. It doesn't seem to read it outside the $each loop. Any ideas what could it be?
I tried using console.log() in the $each loop and it works fine, however, it won't work outside of it.
function solicitare() {
adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, function (raspuns) {
$.each(raspuns, function (indice, examen) {
continutDeAfisat = "<div><i>Subiect: " + examen.examId + "</i>, Student: " + examen.studentId + "</div>";
$(continutDeAfisat).appendTo("#datenoi");
var dategraph = {};
dategraph.examId = examen.examId;
dategraph.studentId = examen.studentId;
});
console.log(dategraph);
stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
}
The error I receive is the following:
You're declaring the variable in an inner scope. So the outer scopes don't know what that variable is. Try:
function solicitare() {
const dategraph = {}; // <---
const adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, function (raspuns) {
$.each(raspuns, function (indice, examen) {
const continutDeAfisat = "<div><i>Subiect: " + examen.examId + "</i>, Student: " + examen.studentId + "</div>";
$(continutDeAfisat).appendTo("#datenoi");
dategraph.examId = examen.examId;
dategraph.studentId = examen.studentId;
});
console.log(dategraph);
const stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
}
Avoid using var and use let instead.
Simply doing myNewVariable = {}; will work, but javascript will not be very happy with you. When declaring new variables always use let or const.
Use const when you wont re-assign a value to a variable.
Use let when you will re-assign a value to a variable in the future.
Local Arrow Functions. Instead of doing:
$.getJSON(adresa, function (raspuns) {
$.each(raspuns, function (indice, examen) {
You can do:
$.getJSON(adresa, (raspuns) => {
$.each(raspuns, (indice, examen) => {
The only time you generally don't want to do this, is when you are working with the this keyword in javascript.
Unused local variables i.e. indice in your case, since you aren't using it. People usually do _ to indicate that it's an unused variable. So you can use either do _indice or _, or even easier, just do (, examen).
String interpolation. As you can see, its pretty annoying to do "<div><i>Subject:" + examen.examId + "....". Instead of "" make the string with ``. Then you can do string interpolation with variables like this ${examen.examId}.
This is what I'd do.
function solicitare() {
const dategraph = {};
const adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, (raspuns) => {
$.each(raspuns, (_, examen) => {
const continutDeAfisat = `<div><i>Subiect: ${examen.examId}</i>, Student: ${examen.studentId}</div>`;
$(continutDeAfisat).appendTo("#datenoi");
dategraph.examId = examen.examId;
dategraph.studentId = examen.studentId;
});
console.log(dategraph);
const stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
}
If you write your javascript in VS code, I can also recommend to install an extension called prettier which will help format your code and make it more readable.
New question: How can I make it that it saves all the answers from the loop and not just one?
Try this:
First, make dategraph an array. Then we push each result object into the array. So something like this:
function solicitare() {
const dategraph = []; // <--- make array
const adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, (raspuns) => {
$.each(raspuns, (_, examen) => {
const continutDeAfisat = `<div><i>Subiect: ${examen.examId}</i>, Student: ${examen.studentId}</div>`;
$(continutDeAfisat).appendTo("#datenoi");
// push result into array
dategraph.push({
examId: examen.examId,
studentId: examen.studentId,
});
});
console.log(dategraph);
const stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
console.log("Final dategraph:", JSON.stringify(dategraph, null, 2));
}

Function inside a Function not calling in React Native

I am new to react-native and calling a function inside a fucntion.
I have done as below so far :
Step 1 : Created a function _snapshotToArray to convert the firebase snapshot to Arrray.
_snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
Step 2 : Created another function as below and calling _snapshotToArray inside it.
_readUserDataFromFirebaseConsole() {//once and on
firebase.database().ref('Users/').on('value', function (snapshot) {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}
Talking about this call :
console.log(this._snapshotToArray(snapshot));
When I press CTRL+CLick, it not letting me to navigate to body of the fuction _snapshotToArray.
In Device am getting below error :
_snapshotToArray is not defined
What might be the issue ?
I'm not at my PC right now, so I cannot test it, but from looking at your code, you need to use a different function notation to allow the varibale access of/from parent methods and parent class.
_snapshotToArray = snapshot => {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
and
_readUserDataFromFirebaseConsole = () => {
firebase.database().ref('Users/').on('value', snapshot => {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}

es6 call class methods within class but also within a on click function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I have this es6 class:
class CommentsController {
constructor() {
this.$addCommentForm = $('.add-comment')
this.$addCommentButton = $('.add-comment input[type=submit]')
}
init() {
this.addCommentFormListener();
}
addCommentFormListener() {
this.$addCommentButton.on('click', function(e) {
e.preventDefault();
let imageId = parseInt($(this).parents('ul').data('id'));
let inputText = $(this).parents('ul').find('.user-text').val();
let comment = new Comment(inputText, imageId);
debugger;
CommentsController.renderComment(comment, imageId)
});
}
renderComment(comment, imageId) {
let image = Image.all[imageId]
image.comments.push(comment)
$('#images').find(`ul[data-id=${imageId}] ul#comments-${imageId}`).append(`<li>${comment.text}</li>\n`);
}
}
The problem is that at the debugger, I want to call the renderComment function but I cannot because this does not refer to the controller anymore. What can I do?
Use an arrow function instead of a function:
An arrow function does not have its own this; the this value of the
enclosing execution context is used.
However, now you can get the clicked element from this, because this refers to the instance. Instead get the clicked element using Event.target:
addCommentFormListener() {
this.$addCommentButton.on('click', (e) => {
e.preventDefault();
const $el = $(e.target);
const imageId = parseInt($el.parents('ul').data('id'));
constinputText = $el.parents('ul').find('.user-text').val();
const comment = new Comment(inputText, imageId);
this.renderComment(comment, imageId)
});
}

Babel es2015 Arrow Function error

I'm using es2015 Arrow functions in a React component that is throwing an error when I declare myfunction() {...}. The error doesn't exist if write it like so myFunction : function () {...}. I do not have any issues compiling with Browserify/Babelify - this only happens with the below example.
import React from 'react';
module.exports = React.createClass({
// render : function () { // <--- this works
render() { // <---- this throws an error
return (
<div>Kaboom.</div>
);
}
});
/* RenderService.js */
require("babel-register")({
plugins: ["transform-react-jsx","transform-es2015-modules-commonjs"]
});
var React = require('react');
var ReactDOMServer = require('react-dom/server');
module.exports = {
renderReport : function (reportId) {
var TestComp = require('./TestCompoennt');
var ReactComponent = React.createFactory(TestComp,'div');
return ReactDOMServer.renderToStaticMarkup(ReactComponent());
}
};
Error: renderApproval() {
^
SyntaxError: Unexpected token (
Maybe you should use a preset-es2015, this plugin includes transform-es2015-shorthand-properties, that one you need to transform this:
var z = function() { return 'z'; };
var x = {
z
}
to this:
var z = function() { return 'z'; };
var x = {
z: z
}
Or in your case
var x = {
z() {
return 'z';
}
}
And also includes:
check-es2015-constants
transform-es2015-arrow-functions
transform-es2015-block-scoped-functions
transform-es2015-block-scoping
transform-es2015-classes
transform-es2015-computed-properties
transform-es2015-destructuring
transform-es2015-for-of
transform-es2015-function-name
transform-es2015-literals
transform-es2015-modules-commonjs
transform-es2015-object-super
transform-es2015-parameters
transform-es2015-shorthand-properties
transform-es2015-spread
transform-es2015-sticky-regex
transform-es2015-template-literals
transform-es2015-typeof-symbol
transform-es2015-unicode-regex
transform-regenerator
Link http://babeljs.io/docs/plugins/preset-es2015/