This might seem reasonable, but if you run this code you’ll quickly find out that this doesn’t work. Well, the control hides alright – but so does everything else <s>. The entire page in fact navigates and it returns a new DOM with none as the value. Slightly unexpected eh? Not quite sure how the browser detects this value, but in any case it navigates the page somewhere I don't want it to navigate to.
There are a few ways around this. First you can navigate with a function call:
This works and appropriately runs the code in the function without navigating the page. However, you have to be careful not to return any values from the function or else you get the same behavior I showed above where the result value becomes the new document displayed.
Since calling a function is OK, you can do something like the following too:
Which essentially defines an inline function and lets you execute the desired code. One downside to this is that the execution context changes so the the this pointer doesn’t point at the control any longer, but at the Window. It’s basically an anonymous function that’s being called on the fly and so it becomes a browser global functon tied to Window.
If you do need the this pointer you can use another approach:
By using onclick() you’re bypassing the navigation operation of the link so you can just use plain in context code to what you need. As you can see in the snippet you can also access the this point in this way.
I'll be at DevIntersection in Vegas this fall giving sessions on ASP.NET Core with Angular and Localization. Thinking of coming? Use discount code STRAHL and save a few bucks. If you do be sure to stop by and say hello!
Other Posts you might also like