I'm trying to store the date and the data from an event source to an object containing the coreid and continue to push the data and date to the correct coreid object.
As of now it's storing the wifiData to both of the coreids instead of the corresponding one. How would I push the data to the right id?
<template>
<div class="container">
<h2>Probe Diagnostics</h2>
<div class="row">
<div class="col">
<line-chart id="wifiChart" ytitle="Signal Strength" label="Wifi Strength" :colors="['#b00']" :messages="{empty: 'Waiting for data'}"
:data="wifiData" height="250px" :library="{backgroundColor: '#eee'}" :download="true" :min="-20"
:max="20"></line-chart>
<column-chart :data="wifiData" ytitle="Signal Strength" height="250px"></column-chart>
</div>
<div class="col">
<line-chart :data="psSoc" ytitle="ps-soc" height="250px"></line-chart>
<line-chart :data="psVoltage" ytitle="ps-voltage" height="250px"></line-chart>
</div>
</div>
</div>
</template>
<script>
let wifiData = [];
let psSoc = [];
let psVoltage = [];
let photons = {};
export default {
data() {
return {
wifiData,
psSoc,
psVoltage,
photons,
}
},
mounted() {
this.streamData();
},
methods: {
streamData() {
// LIVE PUSH EVENTS
if (typeof (EventSource) !== "undefined") {
var eventSource = new EventSource(
"http://10.10.10.2:8020/v1/Events/?access_token=687b5aee0b82f6536b65f");
eventSource.addEventListener('open', function (e) {
console.log("Opened connection to event stream!");
}, false);
eventSource.addEventListener('error', function (e) {
console.log("Errored!");
}, false);
eventSource.addEventListener('WiFi Signal', function (e) {
var parsedData = JSON.parse(e.data);
if (parsedData.coreid in photons) {
photons[parsedData.coreid].push([parsedData.published_at, parsedData.data])
return
} else {
photons[parsedData.coreid] =[]
}
}, false);
eventSource.addEventListener('ps-soc', function (e) {
var parsedData = JSON.parse(e.data);
psSoc.push([parsedData.published_at, parsedData.data])
}, false);
eventSource.addEventListener('ps-voltage', function (e) {
var parsedData = JSON.parse(e.data);
psVoltage.push([parsedData.published_at, parsedData.data])
}, false);
}
}
}
}
</script>
Remove wifiData completely. Instead just manage the array directly inside the lookup object:
// Initialize if needed:
if(!photons[parsedData.coreid])
photons[parsedData.coreid] = [];
// Then push directly to it:
photons[parsedData.coreid].push(/*...*/);
Related
<div id="SearchAddress">
<div class="main_class">
<div class="find_juso_map">
<input type="button" v-on:click="load_juso" value="주소 검색"><br>
<div id="map" style="width:300px;height:300px;margin-top:10px;"></div>
<input type="text" id="sample5_address" placeholder="메모">
<input type="button" v-on:click="add_place" value="장소 추가"><br>
</div>
<div class="set_juso_list">
<h4>요기조아</h4>
<div></div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'SearchAddress',
data() {
return {
center: new window.kakao.maps.LatLng(33.450701, 126.570667),
geocoder: new window.kakao.maps.services.Geocoder(),
joah_add: null,
joah_list: {}
}
},
props: {
},
mounted () {
var container = document.getElementById('map');
var options = {
center: this.center,
level: 3
};
new window.daum.maps.Map(container, options);
},
methods: {
load_juso() {
new window.daum.Postcode({
oncomplete: function(data) {
var addr = data.address; // 최종 주소 변수
console.log(addr,'주소')
this.joah_add = addr;
console.log(this.joah_add ,'조아조아')
// // 주소로 상세 정보를 검색
new window.kakao.maps.services.Geocoder().addressSearch(data.address, function(results, status) {
// 정상적으로 검색이 완료됐으면
if (status === window.daum.maps.services.Status.OK) {
var result = results[0]; //첫번째 결과의 값을 활용
// 해당 주소에 대한 좌표를 받아서
var coords = new window.daum.maps.LatLng(result.y, result.x);
// 지도를 보여준다.
var container = document.getElementById('map');
var map = new window.daum.maps.Map(container, {center: coords,level: 3});
container.style.display = "block";
map.relayout();
map.setCenter(coords);
new window.daum.maps.Marker({position: coords, map: map}).setPosition(coords);
}
});
}
}).open();
},
add_place() {
console.log('장소추가',this.joah_add)
}
}
}
</script>
I want to put joah_add data in the load_juso() and call it in the add_place.
first, I called load_juso() method.
I think, 'this.joah_add = addr;' <- this code can access data and set data: joah_add value.
second, I called add_place method.
why console print joah_add data -> null??
why doesn't it come out like 'this.joah_add = addr'?
please help me :'(
Javascript's this is not bound from the start
but is bound at the time of the call
So your this.joah_add = addr; of this
may be pointing to daum instead of vue
Javascript's this in normal function mode
points to whoever calls it
So
new window.daum.Postcode({... this.joah_add = addr})
could be equivalent to
new window.daum.Postcode({... daum.joah_add = addr})
and not
new window.daum.Postcode({... vue.joah_add = addr})
And your
add_place() {
console.log('장소추가',this.joah_add)
}
should be
add_place() {
console.log('장소추가',vue.joah_add)
}
So here's what you might need to do
load_juso() {
const that = this
new window.daum.Postcode({… that.joah_add = addr;...})
...
}
Hope it can help you
I am stuck on this problem. I am coding a task platform app. Whenever I try to save, the task clones itself. After each "Save Changes," there are more and more clones. I have rewritten the code so many times. But still, I am not successful. Please help me to find the error.
$("#taskSave").click(() => {
const task = {
id: Date.now(),
imageUrl: $("#imageInput").val(),
title: $("#titleInput").val(),
description: $("#descriptionInput").val(),
type: $("#typeInput").val(),
};
$("#overlay").hide();
todos.push(task);
saveStorage(todos);
// reset input values
$("#imageInput").val("");
$("#titleInput").val("");
$("#descriptionInput").val("");
$("#typeInput").val("");
});
function saveStorage(todos) {
localStorage.setItem("todos", JSON.stringify(todos));
display(todos);
};
function display(todos) {
$("#taskBoard").innerHTML = "";
// .html("");
todos.forEach(item => {
let c = document.createElement("div");
c.setAttribute("class", "card");
c.setAttribute('id', item.id);
c.innerHTML = `
<div class="cardTop">
<div class="binContainer">
<div class="binImage"></div>
</div>
</div>
<img src="${item.imageUrl}" alt="task image">
<h2>${item.title}<h2>
<p>${item.description}</p>
<div class="cardType">${item.type}</div>
`;
$("#taskBoard").append(c);
// end
});
};
I've created a minimal working example, and the problem is in the cleanup of the HTML. You cannot use innerHTML on the JQuery object, or you use its html function or you need to retrieve the javascript object with $("#taskBoard")[0].
// You can use:
$("#taskBoard").html("");
// or
// document.getElementById("taskBoard").innerHTML = "";
// or
// $("#taskBoard")[0].innerHTML = "";
// But not:
// $("#taskBoard").innerHTML = "";
The working example here on JSFiddle (on SO dont work localStorage)
let todos = [];
$("#taskSave").click(() => {
const task = {
id: Date.now()
};
todos.push(task);
saveStorage(todos);
});
function saveStorage(todos) {
localStorage.setItem("todos", JSON.stringify(todos));
display(todos);
console.log(todos);
};
function display(todos) {
$("#taskBoard").html("");
// or
// document.getElementById("taskBoard").innerHTML = "";
// or
// $("#taskBoard")[0].innerHTML = "";
// But not
// $("#taskBoard").innerHTML = "";
todos.forEach(item => {
let c = document.createElement("div");
c.innerHTML = `
<p>${item.id}</p>
`;
$("#taskBoard").append(c);
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="taskSave">
SAVE
</button>
<div id="taskBoard">
</div>
I'm learning the basics with Javascript and I'm trying to do a modal that replace an alert, I'm almost done but I have a problem with the querySelector on the button to close it. It returns undefined even if I check it with the if conditional.
function getTemplate(templateName) {
let template = document.querySelector(templateName);
return template.innerHTML;
}
function createFragment(htmlStr) {
let frag = document.createDocumentFragment();
let temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
function putTemplate(template) {
document.body.appendChild(createFragment(template));
}
function openAlert(alertName, btnOpen) {
let openBtn = document.querySelector(btnOpen);
openBtn.addEventListener('click', function () {
putTemplate(getTemplate(alertName));
});
}
function closeAlert(alertName, btnClose) {
let closeBtn = document.querySelector(btnClose);
if (closeBtn) {
closeBtn.addEventListener('click', function () {
let alertWrapper = document.querySelector(alertName);
alertWrapper.parentNode.removeChild(alertWrapper);
});
}
}
function Alert(alertName, btnOpen, btnClose) {
openAlert(alertName, btnOpen);
closeAlert(alertName, btnClose);
}
Alert('#alertTemplate', '.activeBtn', '.deactive');
And this is the markup:
<template id="alertTemplate">
<div id="alertWrapper">
<h1></h1>
<div class="alertBox confirmAlert" role="alert">
<p></p>
<button class="closeBtn deactive troll"></button>
<button class="acceptBtn deactive"></button>
</div>
</div>
</template>
``
I'm using this example but with some modifications. I've added input methods to my app, so user can choose any json file from local pc and read it on a page then choose one more file compare it and see results on the bottom page.
But I'm getting every time error
document.getElementById(...).forEach is not a function
What am I doing wrong? Below my code.. and not working fiddle with the error:
app.controller("Main",function ($scope) {
// ===== Start FileReader =====
$scope.leftWindow = function readSingleLeftFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var leftcontent = e.target.result;
displayLeftContents(leftcontent);
};
reader.readAsText(file);
};
function displayLeftContents(leftcontent) {
$scope.leftElement = document.getElementById('left-content');
$scope.leftElement.innerHTML = leftcontent;
}
document.getElementById('left-input')
.addEventListener('change', $scope.leftWindow, false);
$scope.rightWindow = function readSingleRightFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var rightcontent = e.target.result;
displayRightContents(rightcontent)
};
reader.readAsText(file);
};
function displayRightContents(rightcontent) {
$scope.rightElement = document.getElementById('right-content');
$scope.rightElement.innerHTML = rightcontent;
}
document.getElementById('right-input')
.addEventListener('change', $scope.rightWindow, false);
// ===== End FileReader =====
$scope.results = (function(){
var leftInputIds = {};
var rightInputIds = {};
var result = [];
document.getElementById('left-input').forEach(function (el, i) {
leftInputIds[el.id] = document.getElementById('left-input')[i];
});
document.getElementById('right-input').forEach(function (el, i) {
rightInputIds[el.id] = document.getElementById('right-input')[i];
});
for (var i in rightInputIds) {
if (!leftInputIds.hasOwnProperty(i)) {
result.push(rightInputIds[i]);
}
}
return result;
}());
});
and div
<section ng-show="dnd">
<div class="content">
<div class="row">
<div class="childGrid" style="display: flex">
<div style="width: 50%">
<input type="file" id="left-input"/>
<h3>Contents of the file:</h3>
<pre id="left-content"></pre>
</div>
<div style="width: 50%">
<input type="file" id="right-input"/>
<h3>Contents of the file:</h3>
<pre id="right-content"></pre>
</div>
</div>
<div class="parentGrid">
<div id="compare">
{{results|json}}
</div>
</div>
</div>
</div>
</section>
document.getElementById() returns a single object and not an array.
forEach need an array in odrer to operate it.
forEach method is not defined for object but it is defined for array.
So,that's why you getting an error
document.getElementById(...).forEach is not a function
EDIT1 :
do like this :
var leftInput = document.getElementById('left-input')
leftInputIds[leftInput.id] = leftInput;
var rightInput = document.getElementById('right-input')
rightInputIds[rightInput.id] = rightInput;
I have the following html:
<div ng-show=showMarketingNav>
...
</div>
<div ng-show=showProductsNav>
...
</div>
<div ng-show=showSettingsNav>
...
</div>
What I want to do is to easily be able to hide all but one of the divs from another controller. I thought I could be clever and do the following:
var subNavMenuDisplays = {
Marketing: $scope.showMarketingNav,
Products: $scope.showProductsNav,
Settings: $scope.showSettingsNav
}
$rootScope.hideContextMenu = function () {
for (var category in subNavMenuDisplays) {
subNavMenuDisplays[category] = false;
}
}
$rootScope.setContextMenu = function (name) {
$rootScope.hideContextMenu();
subNavMenuDisplays[name] = true;
}
but this obviously does not work as $scope.showMarketingNav etc. will be passed as value, not reference.
The following works, but is not exactly nice to work with:
$rootScope.hideContextMenu = function () {
$scope.showMarketingNav = false;
$scope.showProductsNav = false;
$scope.showSettingsNav = false;
}
$rootScope.setContextMenu = function (name) {
$rootScope.hideContextMenu();
if (name == "Marketing") {
$scope.showMarketingNav = true;
}
if (name == "Products") {
$scope.showProductsNav = true;
}
if (name == "Settings") {
$scope.showSettingsNav = true;
}
}
Is there a way to grab $scope.showMarketingNav by reference, or another clever way around this?
I'd prefer not using eval to concatenate variable names.
You can place an object on the $scope and then toggle it dynamically:
$scope.show = {};
$rootScope.setContextMenu = function (name) {
$scope.show = {};
$scope.show[name] = true;
}
And the Html:
<div ng-show="show.Marketing">
...
</div>
<div ng-show="show.Products">
...
</div>
<div ng-show="show.Settings">
...
</div>
Here's a plunker demonstrating the change.
You can assign simple updater functions in that object:
Marketing: function(val) { $scope.showMarketingNav = val },
Products: function(val) { $scope.showProductsNav = val},
Settings: function(val) { $scope.showSettingsNav = val}
Then call it:
subNavMenuDisplays[name](true);