Curious if anyone can give me an argument for using one over the other.
Example 1)
XML
<Button id="editGroupBtn" class="groupEditButton" title="Edit" />
JS
function handleEditGroupClick(e) {
//Insert Amazing Code here
}
$.editGroupBtn.addEventListener('click',handleEditGroupClick);
Example 2)
XML
<Button onClick="handleEditGroupClick" class="groupEditButton" title="Edit" />
JS
function handleEditGroupClick(e) {
//Insert Amazing Code here
}
At the moment my superior is arguing he likes the separation of concerns (view only has the view). My argument is issues with adding and removing event listeners (requires more maintenance, more code clutter, and I would assume the code is slower)
Further, the creation of the button is actually in a loop so my argument is that you also don't have to add an ID to listen if you do an onClick (Which I'm a fan of because I don't have multiples of a single ID) but there are other work arounds
Related
I'm testing with blazor and grpc, and I'm trying to follow this tutorial(https://www.youtube.com/watch?v=ynZlJ3pACpI) which seems to be outdated. Either way, with some adaptations it should work, even because there aren't out there many examples or tutorials.
The problem is that the value on the html element is not updated with the grpc response.
I'm supposed to have this:
#page "/greeter"
#inject GrpcService1.GreeterService GreeterService1
#using BlazorApp1.Data
<h1>Grpc Connection</h1>
<input type="text" #bind="#Name" />
<button onclick="#SayHello">Button</button>
<p>#Greetmsg</p>
#code {
string Name;
private string Greetmsg;
async void SayHello()
{
this.Greetmsg = await this.GreeterService1.SayHello(this.Name);
}
}
But something may had been updated because I cannot call the SayHello method that way. I must put the # before the Onclick, otherwise I get the error "Cannot convert method group to no delegate type".
So I put it like this:
<button #onclick="SayHello">Button</button>
This way it works but the result I get from the grpc server only shows up when pressing the button for the next request. I followed the code execution and the request is made, the response comes, but the value on the page isn't updated. Then the code execution ends and still no update. When I press the button for a new request the value somehow is updated.
I also added another button
<button #onclick="SayHello">SayHello</button>
<button #onclick="updateGreetmsg">updateGreetmsg</button>
With an empty function below the other one
public void updateGreetmsg()
{
}
And it is enough to call that function to the earlier received value get shown.
So the await thing is not working in the first function, where it is supposed to.
Anyone knows how to solve this?
It should be async Task SayHello()
Don't use void... use Task instead.
Avoid async void methods
Your button element should be defined as follows:
<button #onclick="#SayHello">SayHello</button>
Note: the onclick attribute is not the normal Html element's onclick attribute. It should be preceded with the '#' sign, and it is called a compiler directive.
Razor components also make extensive use of directive attributes (#onclick, #bind, #ref, and so on) on elements to control various aspects of how components get compiled (event handling, data binding, component & element references, and so on).
Read more...
Note also that after a UI event, such as the above, your component is automatically re-rendered. In the past, we had to call the StateHasChanged method to notify the component that its state has changed, and that it may render. Currently, if you wish to re-render your component due to an alteration of the component's state caused by non UI events, you should call the StateHasChanged method
I understand this may be an elementary question, but I'm new to Asp.net webforms, so please bear with me.
I have a lengthy form on a page that I would like to autosave when users type in a field, or make a selection. The problem is, all I've been able to find online is autosaves that work on a timer. I'd prefer that it saves as the user makes their edits. Also I would like just the individual form element being edited to be sent to the server to avoid sending the entire page back each time.
I've read that I should use a webservice to accomplish this, but since I want to autosave individual items and not the whole form on a timer, how would I set up a webservice to accomplish this? I'm new to webservices I'd like to know what to read up on. Any links are appreciated.
Also, how is the autosave functionality effected when using asp.net validation controls? I've looked around but can't tell if the entire page needs to be valid to make a trip to the server, or if just a single valid item can be sent itself.
Thanks for any help!
If you set AutoPostBack=True on the field, and you add an OnChange event for it (this will vary depending on the type of field the user is interacting with), you can execute a save. Don't call Page.Validate in the methods where you're doing these updates. Call it when you hit the Submit button.
This could cause a LOT of round trips to the server, and it's a lot of code to write and debug.
The Timer approach is one call to one method on a repetitive basis. If you can I'd recommend going with a timer, but sometimes that's not an option.
Generally speaking this is what you'll want to setup on the client-side. Ideally, you will end up with lots of tiny requests which do not require much power on the back-end. This however depends on lots of variables including the database engine you're using.
$(document).ready(function () {
$("input").blur(OnFieldChanged);
});
function OnFieldChanged()
{
var $this = $(this);
var isValid = ValidateField($this);
if (isValid)
{
SaveField($this);
}
}
function SaveField($field)
{
if ($this.val() === $this.prop("oldVal")) return;
var data = {
id: $("idfield").val()
};
data[$field.attr("id")] = $field.val();
$.post({..}).done(function() {
NotifySaved($this);
$this.prop("oldVal", $this.val());
});
}
function ValidateField($field)
{
// Validate the field with your method of choice, manually call Microsoft's client-side validate function or switch to jquery validate.
return true;
}
I have a simple template which has a search box in it:
<template name="search">
<input type="text" name="search" id="search" />
{{> search_results}}
</template>
and obviously, the search results template:
<template name="search_results">
<ul>
{{#each results}}
<li>{{this.resultValue}}</li>
{{/each}}
</ul>
</template>
There is an event for keyp on the search input:
Template.search.events({
'keyup input#search': function (e) {
// fetch result from db
}
});
My problem is, where i have the comment: fetch result from db how do i get the search results template to auto update with the results from the db query?
To be clear: i can get the results fine, just cant see how to get the results template to update.
Essentially, something in the template you want to rerender (search_results) has to be reactive and register a changed event. Out of the box, that means it could be any of the data sources listed here. Since this isn't happening for you, I assume that when you "fetch results from db" you're not actually returning the result of a minimongo query, as this would be reactive by default.
If so, this kind of problem is often most easily solved by rolling your own reactivity using the Deps.Dependency prototype, which (as I understand it) underpins all the other reactive data sources other than the minimongo itself.
If you set var resultsChanged = new Deps.Dependency(), you get an object with two methods: depends and changed. Invoke the former in any computation you want to rerun when it changes and the latter to register a change. Session variables are basically just key/value stores with these Deps.Dependency methods attached to their get and set methods respectively.
So if you have resultsChanged initialised, you just need to make sure your search_results template depends on it, either by adding a new helper function (if results is in the data context as opposed to being a call to a helper), or amending the results helper itself. I'll assume the latter, but adding a new helper instead would be equally trivial.
Template.search_results.helpers({
results: function() {
resultsChanged.depend();
// get your results from wherever
return results;
}
});
That will rerun every time resultsChanged changes, so you just have to add the appropriate code in your callback when you fetch the results:
'keyup input#search': function (e) {
// fetch result from db, passing "resultsChanged.changed()" in a callback
}
Obviously, if the result fetching is synchronous, you don't even need to pass a callback, you can just do it on the next line.
I hope that is vaguely helpful - please let me know if it's not. If my assumption that you're not just pulling something out of the database is wrong, then this is probably on totally the wrong track, so I would recommend posting your actual "fetch result from db" code in your question.
I have an Asp.net page which requires certain sections to be partially updated automatically at an interval of 5 seconds.
I was planning to use the good old Timer control with the AJAX Update Panel for this purpose, but after a bit of reading on this control i found out that it may have some problems especially if,
1) The time difference between the async event performed ( 4 seconds ) by the update panel and the Timer's tick interval ( which is 5 seconds ) are quite small, the update panel will be held up in the async operation all the time.
2) Also, the fact that timer control doesn't work very well with Firefox.
I just wanted to get your opinion as to whether if i should go ahead with the timer and update panel approach, write some custom javascript that does the partial page update or some other strategy altogether.
Personally, I tend to think that the DIY approach is better -- easier to debug and easier to write.
You can use a javascript setInterval for a timer, and every time the function is called, you can initiate an ajax request to your asp.net code-behind to fetch whatever data needs to be updated.
For example, let's say you simply need to, every 5 seconds, update the current time on a page. Let's assume you have a span of ID currentTime on your page, something like:
<asp:Label id="CurrentTime" runat="server" CSSClass="currentTimeLabel" />
In your initial PageLoad event, you set the time:
protected void PageLoad(...)
{
CurrentTime.Text = DateTime.Now.ToString();
}
Now you need to define some javascript on your page that will, every 5 seconds, call the code-behind and get the new date/time value.
Doing this with something like jQuery is very simple:
$(document).ready(function() {
setInterval(5000, updateTime);
});
function updateTime() {
url: "myPage.aspx/SomePageMethod",
success: function(data) {
$(".currentTimeLabel").text(data);
});
}
In ASP.NET, getting the PageMethod to work is the trickiest part (for me, anyway). You need to create a public function in your code-behind with a 'WebMethod' attribute. Something like this:
[WebMethod]
public static string GetCurrentTime()
{
return DateTime.Now.ToSTring();
}
I didn't test any of this code, but the basic premise is sound and should work fine.
Now, this may seem more complicated than using an UpdatePanel, but I find it easier when I know what code is actually running on my page.
If you need to update a series of controls instead of just one control, you can use a more complicated web method that returns xml or json data, and then parse that using javascript.
I am intending to develop a Finite State Machine in the following manner.
Extract Control IDs from a --> web-page,
Write control IDs to a XML --> Controls-XML.
Manually declare States and Transition in the --> Controls-XML
Scan Controls-XML and attach pre-declared Jscript to eventhandlers embed them in the --> web-page..
5.
How feasible this would be..
Am I getting into can of worms ?
First, we live in a can of worms!
your questions are a bit vague, please provide more details if i'm missing your point and maybe this should be beak in parfts to deepen the discution in part details
assuming you want to work live on a client side browser over any page
by extrating ID's of controls i supouse it's all controls of a webpage (it could be by clicking or clicking possibly with key combos), but lets be simple.
Extrating ID's
here's a code than might help you:
function scan(e) {
if (e&&e.childNodes)
for(var i=0;i<e.childNodes.length;i++) {
var child=e.childNodes[i];
if (child) {
if(child.id) console.log(child.nodeName,child.id);
scan(child);
}
}
}
note: this was done with chrome, but any browser console will do i think.
just paste the function on the console and then call it like:
scan(document)
and it will list (on console) all elements that have id's showing element type and id... you can filter that eazy by just printing elements of certain tags like INPUT, SELECT TEXTAREA, etc...
About the XML
here browsers get a bit tricky, you can simplify it too your favorite browser, the following functions constructs a XML document given some XML text.
So by this aproach your scan function should compose the xml text (instead of writing to the console) and later we can feed the XML document
function makeNode(text) {
var doc;
if (window.ActiveXObject) {
doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.loadXML(text);
} else {// code for Mozilla, Firefox, Opera, etc.
var parser=new DOMParser();
doc=parser.parseFromString(text,"text/xml");
}// documentElement always represents the root node
return doc.documentElement;
}
other aproach is to create an empty XML document (as the above function does) and the instead of feed raw xml text your scan function should use XMLDOM commands to insert nodes into the document.
Manually declare States and Transition in the --> Controls-XML
this is an hard one, is this (XML doc) info to be copy/pasted and latter edited? is it edited inplace by inserting a bunch of code to build an interface?
many doubts here, but once we have the information in XML format we would be free to use our imagination and decide a format to handle the wanted state changes.
Scan Controls-XML and attach pre-declared Jscript to eventhandlers embed them in the --> web-page
at this point actions depend on methods followed above, but in any case using XMLDOM functions to traverse the xml doc and apply status change or event handlers to the controls is trivial.
controls need not be scanned anymore because we have stored the id's (use getElementById)
i have a form validation system that does something similar, except the XML is predefined and stored on server side, but once loaded it will do just that. attaching event handlers and do status changes based on evaluated expressions.