I have a Svelte based project. I'm using Socket.io on the backend. I was able to pull a data from the backend to the client side as a localsocket. Console log gives correct results. But I can only use this variable in localSocket. How can I export it? I want to use in div as {Player1} and {Player2}.
const localSocket = get(socket);
localSocket.on('RoundPlayers', (describingPlayer, gozetciPlayer) => {
const Player1 = describingPlayer.nickname;
const Player2 = gozetciPlayer.nickname;
console.log(Player1 + " " + Player2);
});
When I try to use it in the following way, I get the error {Player1}, {Player2} is not defined. But console.log is work
<script lang="ts">
...
const localSocket = get(socket);
localSocket.on('RoundPlayers', (describingPlayer, gozetciPlayer) => {
const Player1 = describingPlayer.nickname;
const Player2 = gozetciPlayer.nickname;
console.log(Player1 + " " + Player2);
});
</script>
<div>Next Players: {Player1} and {Player2}</div>
I hope I was able to explain what I mean.
In JavaScript, inner scopes see variables from outer scopes.
So, simply:
<script lang="ts">
...
let Player1
let Player2
const localSocket = get(socket);
localSocket.on('RoundPlayers', (describingPlayer, gozetciPlayer) => {
Player1 = describingPlayer.nickname;
Player2 = gozetciPlayer.nickname;
console.log(Player1 + " " + Player2);
});
</script>
<div>Next Players: {Player1} and {Player2}</div>
Furthermore, Svelte tracks changes to root scope let variables when they are reassigned (in Svelte components only, of course). So with this code, your markup will get updated each time your receive new values.
Related
I'm using the following code to test a state-dependent react component using jest and rtl:
test("render author, date and image correctly after going next post", async () => {
const store = configureStore({
reducer: {
data: dataReducer
}
});
const Wrapper = ({ children }) => (
<Provider store={store}>{children}</Provider>
);
render(<Post />, { wrapper: Wrapper });
const getSpy = jest.spyOn(axios, 'get').mockReturnValue(mockPostJSON);
await store.dispatch(FETCH_POSTS());
expect(getSpy).toBeCalledWith('https://www.reddit.com/r/EarthPorn/.json');
const beforeClick = await screen.findByTestId('authorAndDate');
expect(beforeClick.innerHTML.toString()).toBe(mockPostsList[0].author + ' - ' + mockPostsList[0].date);
fireEvent.click(screen.getByText('Next post'));
const afterClick = await screen.findByTestId('authorAndDate');
expect(afterClick.innerHTML.toString()).toBe(mockPostsList[1].author + ' - ' + mockPostsList[1].date);
})
The problem I'm having is that before the click everything in the store is set up correctly and the authorAndDate element displays the first item in the array of posts. But after the click is fired the store goes back to the initial state it had before loading the mock data. I checked within the component's event handler and right before it does anything the state has been reset. The code is as follows:
const handleNextClick = () => {
store.dispatch(GO_NEXT_POST());
store.dispatch(FETCH_COMMENTS());
}
I've been an hour over the code trying to find something that would reset the state and found nothing. I'm guessing it's some kind of interaction between jest and rtl but I can't figure out why the store in the test has one state and the store in the component's event handler has another :S
Well, figured it out. Can't use store.dispatch directly as it's accessing a stale state. Needed to use the useDispatch hook. Hope this serves anybody who faces the same problem in the future.
This is my first trial to learn to how to scrape images from a web and paste them to Google Sheets. I want to download the second image from https://ir.eia.gov/ngs/ngs.html and paste it to a Google Sheet. In the web, there are two images. I want to get the second image under <img alt="Working Gas in Underground Storage Compared with Five-Year Range" src="ngs.gif" border="0">. I like to learn how to reference its img alt= or src="ngs.gif" in the code, not the index so I can utilize the concept to other various HTML situations also. Can anyone help fix the following code so that I can learn? Thank you!
function test() {
const url = 'https://ir.eia.gov/ngs/ngs.html';
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
var $ = Cheerio.load(res);
// I want to download the image, <img alt="Working Gas in Underground Storage Compared with Five-Year Range" src="ngs.gif" border="0">
// What should be changed in the following code?
var chart = $('img').attr('src').find('ngs.gif');
SpreadsheetApp.getActiveSheet().insertImage(chart, 1, 1);
}
I believe your goal as follows.
You want to retrieve the 2nd image of img tags and put it to the Spreadsheet.
In this HTML, it seems that the URL is https://ir.eia.gov/ngs/ + filename. So I thought that the method of insertImage(url, column, row) can be used. When this is reflect to your script, how about the following modified script?
Modified script:
function test() {
const url = 'https://ir.eia.gov/ngs/ngs.html';
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
const $ = Cheerio.load(res);
const urls = [];
$('img').each(function () {
urls.push("https://ir.eia.gov/ngs/" + $(this).attr('src'));
});
if (urls.length > 1) {
SpreadsheetApp.getActiveSheet().insertImage(urls[1], 1, 1); // 2nd image is retrieved.
}
}
When this script is run, the URL of https://ir.eia.gov/ngs/ngs.gif is retrieved and the image is put to the Spreadsheet.
Reference:
insertImage(url, column, row)
Added:
About your following new question in the comment,
Thanks a lot! So other than calling the index of the image, is there no method to call either alt="Working Gas in Underground Storage Compared with Five-Year Range" or src="ngs.gif" in the code? I'm just curious to learn a smart way for a potential scenario, for instance, if a web has 20 images and the locations of those images keep changing day by day, so the second image is not always in the second place. Thank you again for any guide!
In this case, how about the following sample script?
Sample script:
function test() {
const url = 'https://ir.eia.gov/ngs/ngs.html';
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
const $ = Cheerio.load(res);
const obj = [];
$('img').each(function () {
const t = $(this);
const src = t.attr('src');
obj.push({ alt: t.attr('alt'), src: src, url: "https://ir.eia.gov/ngs/" + src });
});
const searchAltValue = "Working Gas in Underground Storage Compared with Five-Year Range";
const searchSrcValue = "ngs.gif";
const ar = obj.filter(({alt, src}) => alt == searchAltValue && src == searchSrcValue);
if (ar.length > 0) {
SpreadsheetApp.getActiveSheet().insertImage(ar[0].url, 1, 1);
}
}
In this sample script, when the values of src and alt are Working Gas in Underground Storage Compared with Five-Year Range and ngs.gif, respectively, the URL is retrieved and put to the image.
If you want to select Working Gas in Underground Storage Compared with Five-Year Range OR ngs.gif, please modify alt == searchAltValue && src == searchSrcValue to alt == searchAltValue || src == searchSrcValue.
I want to save an element in a variable.
This is my code
var casper = require("casper").create();
var data = "";
casper.start("http://www.naver.com",function(){
data = require('utils').dump(this.getElementsAttribute("#name","cy"));
});
casper.run();
This doesn't work!
If I remove (data =) part, then it makes a log in cmd...
But, I didn't even used this.echo !!
Selector #name doesn't actually exists in www.naver.com
It is too long, so I just used #name for a replacement.
I think you are missing some basic idea about CasperJS... I write a small sample code for you to illustrate extracting data by css selector:
var casper = require("casper").create();
var data;
casper.start("http://stackoverflow.com/users/6571228/cute-developer",function() {
data = casper.evaluate(function () {
return document.querySelector('#user-card > div > div.row.col-content > div.col-left.col-8.about > div.bio > p').textContent;
})
}).then(function () {
casper.echo("result:\n" + data);
});
casper.run();
Output:
$ casperjs evaluate2.js
result:
I wanna be a best Korean woman developer.
Feel free to leave a comment here if you still got some questions about CasperJS...
Ok, I've looked at a lot of examples that don't really appear different from mine. I simply want to do something (right now, just an alert), when a checkbox changes (is clicked, or whatever). My code:
$(document).ready(
function () {
$('input:checkbox').bind('change', function() {
var id = $(this).attr("id").substring(5);
var skill = $("#skill" + id).val();
alert("you processed skill number " + skill);
})
}) ; // end doc ready
One thing that MAY be different from others is that I'm dynamically creating these checkboxes with another script included like this (without the "script" tags here):
<pre>src="jscript/skills_boxes.js" type="text/javascript" </pre> <br>
Currently that is ABOVE my 'problem' but I've had it below and my stuff still doesn't work. Is there some sort of timing issue here? I'd appreciate any help. Thanks.
Use jquery on function.
$(document).ready(
function () {
$('body').on('change', 'input:checkbox', function() {
var id = $(this).attr("id").substring(5);
var skill = $("#skill" + id).val();
alert("you processed skill number " + skill);
})
}) ; // end doc ready
In Backbone.js I am trying to use a variable as a selector to bind to an event like this:
events: function() {
var _events = {};
_events["click " + "#plus-" + this.options.count] = "add";
return _events;
}
Some (or more than one) thing must be wrong because Backbone seems to ignore it.
Most examples I've seen here use class and not id selectors. Is there a reason for that?
Thanks in advance
I have to say that I don't understand this dynamic events declaration need. But I suppose you have your reasons.
Any how I've come up with a working solution that looks like this:
// html
<div id="container">
<button id="button-1">button 1</button>
<button id="button-2">button 2</button>
</div>
// js
var View = Backbone.View.extend({
events: function(){
var _events = {};
_events["click " + "#button-" + this.options.count] = "buttonClick";
return _events;
},
buttonClick: function(){
console.log( "click() on button " + this.options.count );
}
});
var view1 = new View({
el: $('#container'),
count: 1
});
var view2 = new View({
el: $('#container'),
count: 2
});
Check the working jsFiddel
So, either I'm missing something or the issue is somewhere else.
About using class or id in your events css selector it is just up to you.