angular: value generated using interval not reflecting in browser using {{}} - javascript

I am trying to show the value being changed after each second in the web page, but {{}} is not working.
However, I used console.log, which does show changing value.
Here is my .ts code snippet
randomValue: number;
processIncrementValue(){
this.randomValue = Math.floor((Math.random()*100)+1);
console.log("generating random number: " + this.randomValue);
}
// on this function by button press, value starts to change
start(){
console.log("generating random number: start " + this.randomValue);
this.myVar = setInterval(this.processIncrementValue, 1000);
}
.HTML file snippet
<div class="row">
<button type="button" class="btn btn-primary" (click)="start()">Start</button>
<hr>
<div class="row">
<p>my name is: {{randomValue}}</p>
</div>
</div>

Bind setInterval to scope with the ES6 arrow function () =>
this.myVar = setInterval(()=>{this.processIncrementValue()}, 1000);
When you use setInterval(function () { doThing() });, it binds this to the window object. So in the function doThing() if you have this.doSomething, your code wants to find a variable in the window object called doSomething, which doesn't exist.
When you use the arrow function, it binds this to the current scope, which is your angular component.
From: https://www.w3schools.com/js/js_arrow_function.asp
In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions the this keyword always represents the object that defined the arrow function.

You could try this
.TS file
randomValue: number; // = 0 if you need to initialize it
processIncrementValue() {
this.randomValue = Math.floor((Math.random() * 100) + 1);
setTimeout(() => {
this.processIncrementValue();
}, 1000);
}
.HTML file
<div class="row">
<button type="button" class="btn btn-primary" (click)="processIncrementValue()">Start</button>
<div class="row">
<p>my name is: {{randomValue}}</p>
</div>
</div>

Related

Storing an integer variable in local storage in alpine.js

I wanted to store an integer value in local storage using alpine.js
There is a button that increments the value by 1 when pressed.
Here is how I thought it should be:
<div id="greeting" class="inner" x-data="{ $store.integer: 0 }">
<button class="button bouncy" #click="$store.integer+=1" x-text="$store.integer + ' is the number'"></button>
</div>
<script>
document.addEventListener('alpine:init', () =>
Alpine.store('store', integer)
})
</script>
This didn't work. I tried some other implementations, but none of them seemed to work. I also tried not adding the $store, since it showed the integer as "undefined" when I did that.
Alpine has the persist plugin which looks like it might suit your needs.
https://alpinejs.dev/plugins/persist
<div x-data="{ count: $persist(0) }">
<button x-on:click="count++">Increment</button>
<span x-text="count"></span>
</div>
You have a couple of mistakes in the example code. The corrected version is the following:
<div id="greeting" class="inner" x-data="{}">
<button class="button bouncy" #click="$store.integer += 1" x-text="$store.integer + ' is the number'"></button>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('integer', 0)
})
</script>
When you create a new variable in the store, the first argument is the name of the variable, the second is its initial value.
In the component, you don't have to recreate the variable in the x-data attribute, since it is defined in the alpine:init hook. So you can use just an empty x-data (assuming you don't have other variables in the component).
You have a missing { after =>.

Auto Refresh Div container

I have function like:
document.getElementById("IR_0_ph").innerHTML = sent_dict["IR_0"];
and i get this info like: h2 id="IR_0_ph" class="number">0</h2>
All work fine, but he not auto update info, if i manual reloat page all its good, but i need auto update this info.
mb i can refresh just main Div Container or .... ?
function data_handler(sent_dict) {
socket.emit("control_event", {
data: "Hello!"
}); // tell the RPI that the wifi connection is still working
document.getElementById("IR_0_ph").innerHTML = sent_dict["IR_0"];
document.getElementById("IR_1_ph").innerHTML = sent_dict["IR_1"];
document.getElementById("IR_4_ph").innerHTML = sent_dict["IR_4"];
document.getElementById("IR_Yaw_right_ph").innerHTML = sent_dict["IR_Yaw_right"];
document.getElementById("IR_Yaw_left_ph").innerHTML = sent_dict["IR_Yaw_left"];
document.getElementById("Yaw_ph").innerHTML = sent_dict["Yaw"];
document.getElementById("p_part_ph").innerHTML = sent_dict["p_part"];
document.getElementById("alpha_ph").innerHTML = sent_dict["alpha"];
document.getElementById("Kp_ph").innerHTML = sent_dict["Kp"];
document.getElementById("Kd_ph").innerHTML = sent_dict["Kd"];
document.getElementById("blue_percentage_ph").innerHTML = sent_dict["blue_percentage"];
stored_state = document.getElementById("state_table_1_ph").innerHTML;
new_state = sent_dict["AUTO_STATE"];
if (new_state != stored_state) {
insert_into_state_table_ph(new_state);
}
document.getElementById("manual_state_ph").innerHTML = sent_dict["manual_state"];
document.getElementById("mode_ph").innerHTML = sent_dict["mode"];
}
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-lg-3">
<div class="statistic__item">
<h2 id="IR_0_ph" class="number">unknown</h2>
<span class="desc">FRONT SIDE</span>
<div class="icon">
<i class="zmdi zmdi-account-o"></i>
</div>
</div>
</div>
</div>
</div>
1) How data_handler function being called from what way, is it called from some async flow or its just a one time calling function.
2) Where the sent_dict is coming from ?
Not sure How you are calling, and how sent_dict data passing to dataHandler function. Assuming sent_dict is a server call or device response.
There are two use cases or senarios:
1) calling once.
example:
ajaxCall.then(sent_dict => data_handler(sent_dict));
if yes, perform the ajax call in intervals using setTimeout function of javascript.
setTimeout(ajaxCall, interval_time).
or you can use observable interval operator to mimic the same behavior without doing much. which will automatically update the div on each time response gets from server.
2) if it is calling more than once or interval based calling.
following code in not enough to answer your question.

How to pass variable to child function from HTML page

I want to pass a value from HTML page to child function from parent function.
HTML Page:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
<div class="text">Send/div>
</div>
</div>
Parent Function Call:
$('.send_message').click(function (e) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
});
$('.message_input').keyup(function (e) {
if (e.which === 13) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
}
});
here getMessageText1 is child function.
Child Function:
getMessageText1 = function () {
var result="";
var id = Parent_FUNC_INPUT;
$.ajax({
url:"func.php",
type: 'POST',
data: ({id:id}),
async: false,
success:function(data) {
result = data;
}
});
I want to populate [[id]] variable in child function from parent function.
First, I'll do my best to clean up the HTML:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
</div>
<div class="text">Send</div>
</div>
Using proper indentation will make things far easier to read. And while we're on the subject, you may want to use dashes - instead of underscores _ in your class names, as that's the common convention.
On to your question, it seems like what you want to do is simply pass an argument to getMessageText1 from within (as you refer to it) a "parent" function bound to an event listener.
So you'd define this "child" function with a single parameter:
function getMessageText1(Parent_FUNC_INPUT) {
...
var id = Parent_FUNC_INPUT;
...
}
And then you can just call it with getMessageText1(value) where value is whatever you want to pass in.
One more note: for readability's sake I recommend you do not name your functions the way you have. Having two functions getMessageText and getMessageText1 will just be a source of confusion later on. Instead, think of something more descriptive, ala getMessageTextFromID.
Hopefully I answered the question you meant to ask. Let me know.

Pass Anonymous function that requires a parameter, to another function as an argument which will be assigned to an onclick

I have a function that I want to reuse throughout my program. Basically it's a bootstrap dialog box that has a confirm and a cancel button. I setup the helper function to accept two anonymous functions, one for the cancel and one for the confirm. I have everything working except I am not sure how to properly assign it to the onclick when building the html. I want to avoid using a global variable but this is the only way I was able to get this to work.
Custom function:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + cancelFunc + ')()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + confirmFunc + ')()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
I have to do, onclick = "(' + cancelFunc + ')()"> because if I do, onclick = "' + cancelFunc() + '"> it shows up as undefined. The current way will basically just print the anonymous function out and assign it to the onclick (almost as if I just typed out the anonymous function right at the onclick)
here is where I call the function:
var transTypeHolder;
$("input[name='transType']").click(function () {
var tabLength = $('#SNToAddList tbody tr').length;
if (tabLength == 0) {
var selection = $(this).attr("id");
serialAllowableCheck(selection);
resetSerialNumberCanvasAndHide();
$("#Location").val("");
$("#SerialNumber").val("");
}
else {
transTypeHolder = $(this).val();
var confirm = function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+transTypeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
var cancel = function () {};
confirmMessageBox("This is a test", cancel, confirm);
return false;
}
});
Is there a way to some how pass a variable to the anonymous function without using the global variable I have as, "transTypeHolder" ?
Before I get the, "Why are you doing it this way??" response; Javascript isn't a strong language of mine, as I am using ASP.NET MVC4. I haven't had a chance to sit down and learn Javascript in detail and I sort of picked it up and search what I need. So if there is a better way of tackling this, I am open for constructive criticism.
Don't make event handler assignments in HTML at all. If you want people to be able to supply their own functions for canceling and confirming use on:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default cancel" data-dismiss="modal">Cancel</button></td><td><button type="button" class="btn btn-default confirm" data-dismiss="modal">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$("#confirmMsgContainer").off('click', '.confirm').on('click', '.confirm', confirmFunc);
$("#confirmMsgContainer").off('click', '.cancel').on('click', '.cancel', cancelFunc);
$('#ConfirmMsgModal').modal('show');
}
Note that I've edited the HTML you're using to remove the onclicks and added a class to each button. I'm also using off to be sure any previously added event handlers are removed.
As far as passing the variable to the confirm function without using a global, use a closure:
var transTypeHolder = $(this).val();
var confirm = (function (typeHolder) {
return function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+typeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
})(transTypeHolder);
That tells JavaScript to create a function, which returns a function that does what you want it to do. That "function creator" takes in the variable you want to keep around, allowing it to be used elsewhere.
Now, I haven't tested this, so you may have some debugging in your future, but hopefully it gives you a jumping-off point.
You should be able to do it by having the function being acessible from global context under a generated name (which can be multiple if you have more than one instance of the box), like so:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
window['generatedCancelFunctionName1'] = cancelFunc;
window['generatedConfirmFunctionName1'] = confirmFunc;
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedCancelFunctionName1()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedConfirmFunctionName1()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
This way you are not obliged to expose the function code. You can also set an id attribute to the element and set a jquery click() function like in the second part (but you would need the html to be created before you set the click)

How "Data" can help me

I'm doing a web game with javaScript and KnockoutJs library.
In my html file I have a array foreach, and the number that this array saves, is the same number of buttons that a I have to draw on the page. Like this:
<strong data-bind = "foreach: cena1.opcoes">
<button data-bind="click: $parent.teste">Opcão</button>
<font color="red"><strong data-bind="text: conteudo"> </strong></font><br>
What I want to know is, how will I know which button the player selected?
I put data like a parameter on my button function, but I don't know how this works. like this:
object.teste = function(data) {
}
You can call the function this way:
<button data-bind="click: function() { $parent.teste($data); }">Opcão</button>
or
<button data-bind="click: function() { $parent.teste($data/* here can be any arguments available in the current binding context */); }">Opcão</button>
Update
By default the first parameter is being passed to the click handler function is the current view model - $data in the current binding context.
For more details and advanced scenarios you can check the Knockout JS documentation.
The click binding passes the current item to the bound function.
var vm = {
items: [1, 2, 3],
click: function(data) {
alert('You clicked: ' + data);
}
};
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach:items">
<button data-bind="click:$parent.click">Click</button>
</div>

Categories