Documentation event listeners - javascript

I have a question concerning this code down here:
on.("click", () => {...})
Currently I try to figure out Electron. In a code example I saw the use of the usual event listener function. In the fat-arrow function the developer used different kinds of properties. For example:
on.("click", () => {event, bounds})
I am interested in the amount of properties you can use... there are probably more than just those two. I could not find any documentation on this.
That did not help me at all: https://developer.mozilla.org/en/docs/Web/Events/click
Maybe someone can help me out on this.

I assume, what confused you is - Desctructuring assignment.
This code(which is not very correct):
.on("click", () => {event, bounds})
Can be overwritten by this one:
.on("click", e => {
return {
event: e.event,
bounds: e.bounds
};
});

I am interested in the amount of properties you can use...
There are no other properties besides the ones embedded into the event object.
event refers to the global variable window.event which is a reference to the currently handled event.
.on('click', () => { console.log(event) })
and
.on('click', (e) => { console.log(e) })
will output the same event (exept in Firefox, where the first example will not output anything)
I highly suspect that bounds is a variable defined by the author of your tutorial, because the click-event doesn't have a direct bounds property (as you've already seen in the MDN documentation). We'd have to see the full example to explain it where it actually comes from.

Related

Javascript functions in associative array "is not a function"

Recently I learned Javascript ES6 has classes so I tried them but my functions were always giving me errors saying they don't exist. So I made pseudo-classes using javascript associative arrays. It was working absolutely fine until I added some new methods.
Here is the error message I'm receiving:
EventListener.js:132 Uncaught TypeError: this.listen_for_tab_swap is not a function
at HTMLDivElement.<anonymous> (EventListener.js:132)
at Object.alert_eventlistener_of_tabs (EventListener.js:41)
at Object.new_tab (EventListener.js:59)
alert_eventlistener_of_tabs # EventListener.js:41
new_tab # EventListener.js:59
xhr.onreadystatechange # EventListener.js:94
XMLHttpRequest.send (async)
(anonymous) # EventListener.js:101
Here is the relevant code body:
const eventListener = {
listen_for_tab_swap: function() {
$(".footer button").on("click", function (event) {
file_tabs.show_tab(event.target.innerText);
});
},
listen_for_tabs_activation: function() {
$("#AZ_content").on("tabs_loaded", function () {
this.listen_for_tab_swap();
});
},
listen: function() {
$(function () {
console.log("Yeah, I'm listening...");
$(".menu").on("click", function (event) {
AZ_page_is_opened(event);
showTab(event, event.target.id.replace("Button", ""));
});
});
}
};
Please let me know if there is any additional information required to troubleshoot. Thanks in advance for any help.
In js this is dynamic. It depends on how a function is called. I'm assuming you're using jQuery because it looks like jQuery syntax at a glance so for your specific case all you need to know is that in jQuery (and also in regular javascript) the value of this in an onclick event is the element that triggered the event:
{
// ...
listen_for_tabs_activation: function() {
$("#AZ_content").on("tabs_loaded", function () {
this.listen_for_tab_swap(); // this is AZ_content
});
}
In the code above what you are doing is trying to call $("#AZ_content")[0].listen_for_tab_swap() and it is complaining that that HTML element does not have a method called listen_for_tab_swap
There are several ways to fix this. The simplest is probably do:
eventListener.listen_for_tab_swap();
You can also use arrow functions to bind this:
{
// ...
listen_for_tabs_activation: function() {
$("#AZ_content").on("tabs_loaded",() => { // this fixes `this`
this.listen_for_tab_swap();
});
}
There are several more ways to solve this. Check out this answer to another related question for how this actually behaves: How does the "this" keyword in Javascript act within an object literal?

How do I use a function as a variable in JavaScript?

I want to be able to put the code in one place and call it from several different events.
Currently I have a selector and an event:
$("input[type='checkbox']").on('click', function () {
// code works here //
});
I use the same code elsewhere in the file, however using a different selector.
$(".product_table").on('change', '.edit_quantity', function () {
// code works here //
});
I have tried following the advice given elsewhere on StackOverflow, to simply give my function a name and then call the named function but that is not working for me. The code simply does not run.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals() {
// code does not work //
}
});
So, I tried putting the code into it's own function separate from the event and call it inside the event, and that is not working for me as well.
calculateTotals() {
// code does not work //
}
So what am I doing wrong ?
You could pass your function as a variable.
You want to add listeners for events after the DOM has loaded, JQuery helps with $(document).ready(fn); (ref).
To fix your code:
$(document).ready(function() {
$("input[type='checkbox']").on('click', calculateTotalsEvent)
$(".product_table").on('change', '.edit_quantity', calculateTotalsEvent)
});
function calculateTotalsEvent(evt) {
//do something
alert('fired');
}
Update:
Vince asked:
This worked for me - thank you, however one question: you say, "pass your function as a variable" ... I don't see where you are doing this. Can you explain ? tks. – Vince
Response:
In JavaScript you can assign functions to variables.
You probably do this all the time when doing:
function hello() {
//
}
You define window.hello.
You are adding to Global Namespace.
JavaScript window object
This generally leads to ambiguous JavaScript architecture/spaghetti code.
I organise with a Namespace Structure.
A small example of this would be:
app.js
var app = {
controllers: {}
};
You are defining window.app (just a json object) with a key of controllers with a value of an object.
something-ctlr.js
app.controllers.somethingCtlr.eventName = function(evt) {
//evt.preventDefault?
//check origin of evt? switch? throw if no evt? test using instanceof?
alert('hi');
}
You are defining a new key on the previously defined app.controllers.somethingCtlrcalled eventName.
You can invoke the function with ();.
app.controllers.somethingCtlr.eventName();
This will go to the key in the object, and then invoke it.
You can pass the function as a variable like so.
anotherFunction(app.controllers.somethingCtlr.eventName);
You can then invoke it in the function like so
function anotherFunction(someFn) { someFn();}
The javascript files would be structured like so:
+-html
+-stylesheets
+-javascript-+
+-app-+
+-app.js
+-controllers-+
+-something-ctlr.js
Invoke via chrome developer tools with:
app.controllers.somethingCtlr.eventName();
You can pass it as a variable like so:
$(document).ready(function() {
$('button').click(app.controllers.somethingCtlr.eventName);
});
JQuery (ref).
I hope this helps,
Rhys
It looks like you were on the right track but had some incorrect syntax. No need for { } when calling a function. This code should behave properly once you add code inside of the calculateTotals function.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals();
});
$("input[type='checkbox']").on('click',function() {
calculateTotals();
});
function calculateTotals() {
//your code...
}
You could just condense it all into a single function. The onchange event works for both the check box and the text input (no need for a click handler). And jQuery allows you to add multiple selectors.
$('input[type=checkbox], .product_table .edit_quantity').on('change', function() {
console.log('do some calculation...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product_table">
<input type="checkbox">
<input class="edit_quantity">
</div>

Where does e come from in Jquery and JS?

so i have been programming JS for a while now , and basically i never really understood one thing , I.E. the e in events , have a look at the code below :
have a look at the HTML code :
Hello
Jquery code :
$(function () {
$('a').click(function(e){
console.log(e.target)
})
});
now what is e in the above code , i understand the following :
e is an object normalized by jquery and is being internally passed
also i have come across the following explanation :
The functions you are referring to are called callback functions.
Parameters for those are passed from within the function that is
calling them ( in your case .on() or .click() )
to better illustrate how callback functions work here is an example
function customFunction ( param1, callback ) {
var response = "default response";
if (param1 === "hello") {
response = "greeting";
}
callback(response);
}
customFunction("hello", function(e) {
console.log("this is " + e);
}); // > this is greetings
I have read a famious thread on SO here. , but it only answers what e is and not where it comes from .
BUT I still don't understand where that e is coming from . can somebody explain in a bit of detail ?
Thanks .
Alex-z
When using jQuery the e parameter (which you can rename to anything you like) is going to be an Event object passed to your event handler method by jQuery. The Event object is jQuery's wrapper type for browser event interfaces so that you can have a standard interface in your handlers see here - jQuery.
That type has a property called 'target' which points to the original native browser event interface that jQuery was given by the browser. For example for mouse clicks the native interface would be this for example. Note actual interface may differ across browser implementations particularly older ones which is why jQuery attempts to provide some consistency via their type.

onclick attribute doesn't find global function

I dinamically add divs with onlick event, but clicking got an error (Mozilla Firefox): "ReferenceError: myfoo is not defined". If I change onclick event to alert, it works fine, but non with mysefl written functions.
Here is jsfiddle
http://jsfiddle.net/UJ85S/5/
function myfoo(x)
{
alert(x);
}
$("#some").html('<div id="cool_div" onclick="myfoo('+"'xwe'"+');"></div>');
Can you, please, explain what is wrong?
(I understant that can assign.click event, but is it possible through onclick?).
What you really need to do is not let jsFiddle wrap it inside the onload event as this uses a function which creates new scope. Your function is then not accessible outside this new scope. Learn what's happening not learn how to get around it (i.e. not just hack your code to the window Object):
http://jsfiddle.net/UJ85S/12/
No wrap - in <body>
This is happening because you define myfoo inside of $(window).load(function () {...}) function (JSFIDDLE does this):
You need to declare a global function. You can do window.myfoo to declare your function instead.
window.myfoo = function (x)
{
alert(x);
}
JSFIDDLE
But yeah, it's not a good practice to polute the global scope, that's why it's better to use $(...).on("click", function () { alert(...) }) handlers.
I discourage using on... attributes in HTML because it's also another bad practice.
Your code becomes:
function myfoo (x)
{
alert(x);
}
var $divToAppend = $("<div id='cool_div'>")
$divToAppend.on("click", function () {
myfoo("hello");
});
$("#some").html($divToAppend);
And here a DEMO.

How to register event handlers for TypeScript declarations

I've asked this question on typescript's codeplex forums but didn't get an answer so I'm asking here. For a given TypeScript class declaration, for example the Bing Maps one (https://bingmapsts.codeplex.com/) how would someone register an event handler?
On the Map class (in Microsoft.Maps.d.ts) there are a couple of events declared:
viewchange: () => any;
viewchangeend: () => any;
viewchangestart: () => any;
And I've tried hooking a function like the following inside a typescript file but it never gets called:
///<reference path="Bing/Microsoft.Maps.All.d.ts" />
window.onload = function()
{
var map = new Microsoft.Maps.Map(document.getElementById('map'),
{
backgroundColor: 0,
});
map.click = () => alert('click');
map.viewchangestart = () => alert('viewchangestart');
}
In traditional javascript, I would use the following:
Microsoft.Maps.Events.addHandler(map, 'viewchangestart', function (e)
{
alert('viewchangestart');
});
but there is no such method in the typescript declaration and since I can't seem to reference the virtual earth map control from a .ts file I'm not sure how I can do this.
The definition (https://bingmapsts.codeplex.com/SourceControl/latest#BingTS.Solution/BingTS/Bing/Microsoft.Maps.d.ts) is wrong : http://msdn.microsoft.com/en-us/library/gg427609.aspx Those functions do not exist. You can only register events via the addHandler. Simple definition:
declare module Microsoft.Maps.Events{
function addHandler(map:Microsoft.Maps.Map,event:string,func:Function);
}
It's very likely the .d.ts file is simply wrong. They are usually hand-authored and should not be considered authoritative. I don't see any reference to a viewchangestart event object in the options parameter in the API reference, so whoever was writing that file probably just misread the documentation.
In terms of statement- or expression-level code, whatever you would have written in JavaScript, you should write in TypeScript. There's not any difference in terms of how external APIs are used.

Categories