Multiple event listeners on HTML5 canvas - javascript

I've been trying to create a game in strictly HTML5 and JavaScript and have run into an issue that I can't seem to wrap my head around. In an attempt to try and avoid using third party classes/libraries, I'm creating my own class for handling custom buttons within the HTML5 canvas element. I almost got them to work and then had to re-write most of the script after realizing that my event listeners kept adding on top of each other every time the canvas redrew (I was using an anonymous function in the mouseDown event listener before, but have since switched to a different method).
First of all, my event listeners now use a function which holds a reference to whichever button I'm trying to use. My prototype's mouseDownFunc is then called, it checks the boundary of the button instance's dimensions, and then finally calls a referenced onPress() (which is actually an overridden method that every button uses, so each button has a custom set of instructions when pressed).
So, if you're still following along (I know, it's a bit confusing without seeing the full script), the problem is that because my event listeners are using the same function, they're overwriting the previous event listener, so only the last button added functions correctly. To sum this all up, how can I add multiple event listeners to the canvas element, which all use the same function without erasing the previous event listeners. Note that I'm trying to do this without the use of jQuery or other third-party extensions.
If more information is needed in regards to my code so that it's easier to understand, let me know. Thanks in advance for any type of feedback.
Edit: Perhaps this might help. Note that this isn't the complete code, but contains the main points:
Adding a button:
this.test_button = new CreateButton(this, 'test_button');
this.test_button.onPress = function() {
alert('Blue button works!');
};
this.test_button.create(200, 50, 30, 200, 'text');
When using create() on a button, variables are checked and stored, as well as an array that holds onto all current buttons (so they can be referenced at any point). Then this is run: this.that.custom_canvas.addEventListener('mousedown', this.create.prototype.mouseDownFunc, false);
When mouseDownFunc is called, this takes place:
CreateButton.prototype.create.prototype.mouseDownFunc = function(e) {
var mouse_x = e.clientX-this.offsetLeft;
var mouse_y = e.clientY-this.offsetTop;
// Check if the mini-button button was actually clicked
if(mouse_x >= test2.x && mouse_y >= test2.y && mouse_x <= (test2.x + test2.width) && mouse_y <= (test2.y + test2.height)){
alert('clicked and working!');
test2.onPress(); // A reference to the saved function
}
};
Currently, my test2 is a reference to any given object -- it's a global var, but after I get these other issues fixed, I'll deal with getting rid of the global var (I know, I know - it was just a temporary quick-fix).

Maybe instead of an event listener for each and every possible button, and checking box size within the function, you could create a single event that calls a routing function to check where on the element the event occurred, and then delegate to another function

You need to design something to handle the event dispatch in your program. You seem to have components that have their listeners all disorganized. You could build a tree data structure (https://en.wikipedia.org/wiki/Tree_%28data_structure%29) that is a hierarchy for the event dispatch in your components ( such as buttons, text areas etc.). The idea is that when the tree is traversed the events will be handled in an ordered fashion. The tree would be reorganized based on how the user interacts with your program. For a simple example, to start this tree could perhaps prioritize the most recently drawn component (out of some structure that holds a list of everything to be drawn) as the event listener to receive event handling first. Then, if a component is blocked by another component the blocked component (like a button covering the button) it's event handling could either be disabled or scheduled to happen later depending on your implementation. Of course your implementation may be more complex, but you need to keep track the event handling. Java uses a component heirarchy data structure to handle a wide variety of GUI events that you can learn more about here http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

Related

How to remove an event listener from the dom in vue when another event is triggered

I am using Devextreme and Vue.js, and I ran into a rather interesting problem. (Perhaps it is due to lack of understanding of Vue's reactivity system.) I have a method that attaches event handlers to a DOM element that is within a devextreme component at runtime like so (Not the best solution, but it is all I could think of at the time.)
onFocusIn:(e)=>{
let element = e.element.childNodes[1].childNodes[0].childNodes[0];
let selectedElement = element.id.substring(element.id.lastIndexOf("_")+1, element.id.length);
//..............
///.......
element.addEventListener("click",this.moveCursorToFarLeftStupidBug);
element.addEventListener("mouseover",this.moveCursorToFarLeftStupidBug);
},
NOTE: this onFocusIn event pertains to a dx text box dx form simple item, if that matters.
What I would like to do is remove the event handlers on the following event below and not have to wait until the component is destroyed to do so if possible.
This is the event that I wish to utilize to remove the event handlers:
onFocusOut:(e)=>{
let element = e.element.childNodes[1].childNodes[0].childNodes[0];
element.removeEventListener("click",this.moveCursorToFarLeftStupidBug);
element.removeEventListener("mouseover",this.moveCursorToFarLeftStupidBug);
}
However, when I tried to do this, the event handlers would not get purged and I was still able to capture events for mousing over and clicking on the element in question.
I read that the "best place" to remove attached event handlers in Vue is within the beforeUnmount() lifecycle hook, however, I would like to remove these before the component is destroyed. I even tried using this.$nextTick and this.$forceUpdate to update the DOM, but to no avail. Any answer or corrections that need to be made are welcome. Thanks!

Can I trigger an event on a GWT widget using jQuery?

I am trying to automate a website that was built using GWT. My automation uses jQuery to select an appropriate element and then call the jQuery click() function to trigger a click event.
However, the expected action doesn't take place. Clicking the element with the mouse brings up a dialog box, but using jQuery does nothing. If I use jQuery to add a new click handler, I see the new handler executed in both cases, but the original handler only in the "real" click case.
Stepping into the Javascript code, I see very complicated code dealing with stack depth, leading me to think doing this automation may not be directly possible.
Does anyone know of a way to programmatically fire an event on a GWT-generated element? Or should this be working normally, and this site uses uniquely complicated code?
Edit: The code I'm using is quite simple:
var searchButton = jQuery('div.GH1CUEEFLB.GH1CUEEMLB:first');
if (searchButton && searchButton.length > 0) {
searchButton.click();
}
Stepping through the code shows that it selects the correct element, and proceeds to call click(). The existing event handler for the widget, according to Chrome's debugger, is complicated. Stepping through the process leads to a rabbit hole that is quite difficult to follow:
function(){
var stackIndex, returnTemp;
$stack_0[stackIndex = ++$stackDepth_0] = null;
try {
returnTemp = entry0(($location_0[stackIndex] = '57' , jsFunction), this, arguments);
$stackDepth_0 = stackIndex - 1;
return returnTemp;
}
catch (e) {
throw $location_0[stackIndex] = '63' , e;
}
$stackDepth_0 = stackIndex - 1;
}
The solution in this case was to trigger the click event on one of the child elements within the div. The event handler was attached to a particular div surrounding all the components of the button (label, icon, borders, etc). Triggering the event on that parent element did nothing. However, if I instead selected one of the leaf nodes in that subtree (say, the label itself), then triggering the click event brought up the dialog box as desired.
I guess the event handler's code was actively determining the exact element that triggered the event, but was not expecting the parent div to be that trigger source.
var searchButton = jQuery('div.GH1CUEEJT:first');
The above selects the leaf node upon which to trigger the event, even though the parent node 'div.GH1CUEEFLB.GH1CUEEMLB' held the event handler.

jQuery click event handler attached to dom element

I am having hard time while building e-commerce cart module with jquery.
Lets say that if i write a tags in html like this:
<div class="add-to-cart">+</div>
and then target it in my app:
this.$products,
this.$pa,
this.$ip,
this.$products = $('.shopperProducts'),
this.$pa = this.$products.find('.shopperAdd');
var self = this;
this.$ip = function() {
var init = function(action, product) {
/.../
};
self.$pa.on('click', function(event) {
event.preventDefault();
init('add', this);
});
};
This method is possible while im displaying products because they are displayed by php on page refresh so i have all the + links generated by php on html.
The problem is on the checkout file, this is the page when i display entire cart filled with products, cart must be generated and handled in jQuery and AJAX.
And code that i showed you doesnt work in cart page beacuse those links are appended for each product via jQuery into the DOM.
I have been study possible methods and there are few, the most in favour is to do this:
$(document).on('click', self.$pa, function(event) {
The problem with that solution is that it also is considered practice to be avoided due to high resources drain, i can see the difference in execution time myselfe, it takes a lot longer on low end devices. Is there some neat trick that can be used or method that is considered good practice to do in that situation?
<--- EDIT (Solution) --->
Instead of calling:
this.$products = $('.shopperProducts'),
this.$pa = this.$products.find('.shopperAdd');
on the beginning, i have to call it after i load elements into DOM and then they became targetable, then i just have to use self.$ip(); and event handlers can be attached. Without using any sort of workarounds, the solution was just to change order of executing commands.
There are two main strategies that you can use for adding click handlers for elements that you dynamically add to the dom.
One, You can add click handlers to the DOM element each time you create one
var addToCartButton = $('<div class="add-to-cart">+</div>');
addToCartButton.on('click', function(){
init('add', this);
};
// then you add your DOM element to the page
$('.container').append(addToCartButton);
Two, you can have a master click event listener on the page listen for all clicks where your buttons fall, and in your click handler, figure out whether the user is clicking on your element or not. This is ultimately more efficient and you don't have to add or remove event handlers each time you add elements to your page. This pattern is called event delegation, and here's another post on Stack that probably explains it better than I can
What is DOM Event delegation?
$('.container').click(function(event){
if ($(event.target).is('.add-to-cart') || $(event.target).parents().is('.add-to-cart')) {
// handle add to cart
}
})
BTW, your use of the self variable doesn't actually do anything, and neither does declaring this.$pa. You're basically accessing the property "$pa" of your this object, but not doing anything it.

Wicket - IE8 - Javascript event listeners arent executed, when tags are dynamically added over ajax

I have spent several hours, maybe days stucked on a very weird problem :(
I am creating an application that is based on the Wicket solution. It works perfectly in IE9,IE10, Chrome and FF. Strange is, that i have tested it in IE8 too and it works in 99% of cases (IE instances on different computers + totally identical version of IE8) too. But now the PROBLEM.
PROBLEM:
I am creating dynamic content over AjaxLink button. After clicking the button the WebMarkupContainer model is changed and WebMarkupContainer is refreshed (based on Ajax, so the page isnt reloaded complete, but only the container is).
Every item in the container has added AjaxFormComponentUpdatingBehavior. In onComponentTag method, i add tag.put("onchange","some jsFunctionCalling....");. The problem is, that after clicking on the item, no event is invoked. I have tried add the onchange listener over .add(new AttributeModifier.....), but the result is still same. As i have said, i tried the same code in the same version of IE on another PC and it works perfectly. Interesting is, that after refreh of the page everything work perfect, until new item to WebMarkupContainer is added. After that no item listeners work until the page is refreshed again.
One of the latest idea, that i got is, that problem isn't in the code, but in the settings of IE (maybe security). Have anybody any idea? What setting could be set different and cause these problems? Is there any settings on Wicket site, that can solved this? Is there some setting that can blocked registration of these listeners to DOM, if they are added dynamically over ajax?
I didn't tried it but IMHO there are three options you can try:
Instead of adding "onchange" by yourself, add OnChangeAjaxBehavior and make all work in wicket. Downside is server roundtrip on every event.
Add data-attributes (AttributeModifier.append("data-param1", "foobar")) to push your parameters into html and call ajaxRequestTarget.appendJavaScript("attachOnChangeHandler()"); after the click event on the AjaxLink. attachOnChangeHandler() should be your js function to add onchange handler to every item which needs it. And over data-attributes you can access your parameters.
Since Wicket 6: To avoid mixing to much js with Wicket, you could subscribe to one of the global AJAX events.
The solution in your case would be almost the same as in 2. Just add a listener in js for "/ajax/call/success"
(see if the call relates to your component by checking the id) and add the onchange handler there.
This is IMHO the best solution without mixing custom js with Wicket.
The solution provided by #peterchon (attaching event handlers higher in the DOM than the elements which are going to be replaced by wicket) would work in every other case, but you have "onchange" which applies only to input, textarea and select elements.
BTW the page is "working" after refresh, since the whole page is rendered and browser can properly attach the handlers.
You can try this method:
/* this will catpure the target that triggered the event */
function getEventTarget( e ) {
e = e || window.event;
return e.target || e.srcElement;
}
function doSomething( e ) {
var that = getEventTarget( e );
if( that.tagName.toLowerCase() === 'a' ) { // specify the target, in this cas <a>
// Do something
}
}
parentElement.onclick = doSomething;
This script basically will capture any event, then will pass the variable of target to the function that will perform something.
Hopefully this will work for you.
You try to achieve something using a non-wicket JavaScript/Ajax way. This is fine, but also makes it very messy.
Please check this fine article about passing parameters from JavaScript to wicket and vice versa. I think it will suit your needs.
http://wickedsource.org/2013/01/07/rolling-your-own-ajax-behavior-with-wicket/

jquery event added multiple times

I have a fairly large javascript class that generates an complete ajax-generated application. In one version of the ajax page there are a number of dropdown menus. These menus can get created and destroyed at various points during the life cycle of the application.
This is the behaviour I see:
User opens page version 1: no dropdowns
User goes to page version 2: dropdowns added with jQuery onchange event. Work as intended.
User returns to version 1 of page, dropdowns removed.
User returns to version 2 of page, dropdowns added again (using same element IDs)
dropdowns will now have 'double' event handling, triggering the event for each onchange.
The behaviour I'm struggling with is as follows.
On the initial page load, I add an onchange event:
function myClass(){
//Initiate once for current and future elements.
jQuery(document).on('change',".mydropdowns",
function(e){
self.submitDescriptionChange(this);
}
);
}
myClass.prototype.submitDescriptionChange = function (el){
doSomeAjaxStuff();
}
This works fine, except that each time the user goes to pages version 1 and returns to page version 2, the event gets multiplied. Very quickly you can end up with the event firing 20 times per change event, which in this case creates 20 ajax calls.
Logically, by using jQuery.off() I should be able to avoid this. But what happens instead is that the event is removed from both past and future elements, which means that when I recreate page version 2, the dropdowns won't work.
Every way I have tried this (and I've tried LOADS), I either end up with no event firing, or multiple events firing. I cannot seem to find a way to add/replace the elements whereby the event is only ever fired once.
Any ideas how I can solve this?
UPDATED
Yeah, so it turns out I misdiagnosed the problem. It actually came from repeatedly rebinding a 'hashchange' event, rather than rebinding the onchange event. Apologies for misdirection. Moving to bind() function to somewhere where it only executed once fixed the issue.
Since you do not want .off() to remove your events from other pages, I would suggest using namespaces for your events. For example, something like this:
function myClass(pageno) {
var pref_ev = 'mypage' + pageno + '.' + 'change';
$(document).off(pref_ev).on(pref_ev, ".mydropdowns", function(e) {
self.submitDescriptionChange(this);
});
}
This way, each page will have its own "change" event such as "mypage1.change". The event is still registered normally as a change event; the prefix namespace "mypage1" is used to only perform the .off() call on the right events.
I am not sure what plugin you are using for your dropdown menus but there should be a "destroy" method on that plugin. If you call that when removing the dropdowns that should work. Also, if you are only hiding the second page and not actually removing it from the DOM you dont have to re-invoke the plugin as the plugin will still be saved on the element.

Categories