Creating an instance inside a handler function with parameter - javascript

I have this:
Ext.define('MyWindow',{stuff that uses param});
Ext.define('widget.panel',{
stuff
handlerFn: function (parameter) { //parameter comes from Ext.pass(this.handlerFn,parameter)
Ext.create('MyWindow',{param: parameter}).show();
}
stuff
});
The button and its handler are defined inside the initComponent of the panel. When I made this without using Ext.define on the window and directly hardcoding it in the handler instead everything worked fine. However now it says param is not defined. How to pass it correctly?

The handler has to be passed through Ext.pass(this.handlerFn, [parameter])
Also inside the Ext.define make sure you know what your scope is on every level and you will easily find the parameter on the 'window' level.

Related

Phaser 3 this.add.graphics works inside create function, but not outside?

When I add graphics to a scene with this.add.graphics inside of the create function, it works fine, graphics are added. When I try the same code inside of a custom function, say a function called redrawGame(), I get an error message saying:
Undefined is not an object
How can add graphics to a scene outside of the create function?
Depening on your code and code structure, you probably will have to pass the scene ( in this case this) to the custom function, since the this object in the custom function refers to a different object.
// if you want to call it from the "create" function
function create(){
redraw(this);
...
}
...
// Or if you want to call it from the "update" function
function update(){
redraw(this);
...
}
...
function redraw(scene){
scene.add.graphics();
...
}
But without seeing your code, I can't say, if this is your issue, or if there is a different problem.
Update, for custom function call on window resize-event :
To check for the resize Event of the browser/window, I would use the phaser events (link to documentation):
// setup in the create function
this.scale.on('resize', resizeGame, this);
the third parameter is the scope of the callback function (in this case scene), so your resizeGame function would have to call redraw, like this:
function resizeGame(){
...
redraw(this); // due to the scope passed third parameter of 'this.scale.on'
...
}

In this context, what exactly does $('id').on('click', this.method.bind(this)) do?

Here is the app I'm referring to:
I am trying to fundamentally understand the bind method in Javascript.
My understanding when I play around with it in the console is that bind returns a copy of the function, with "this" bound to whatever you pass into bind.
function logThis(){
console.log(this)
}
logThis.bind({today: 'Tuesday'})
//Will return a copy of the logThis function, with 'this' set to the
{today:'Tuesday'} object. The code does not run right away though.
var explicitlyLogThis = logThis.bind({today: 'Tuesday'});
explicitlyLogThis(); //This will run the code and display the {today: 'Tuesday'} object to the console.
This is my understanding so far. I understand that to actually run this new function that has 'this' explicitly bound using the bind method, you need to set it to a variable and then run it.
I see a contradiction when I look at the app in the above link. If you look at the bindEvents method on line 56, we have .on('keyup', this.create.bind(this)). I understand that we have to set 'this' to App when we run the create method because jQuery defaults to setting 'this' to the jQuery object itself. So this line is actually the same as: $('#new-todo').on('keyup', App.create.bind(App)).
That isn't where my confusion is. My question is:
How exactly are these copies of the functions with 'this' set to App actually being called? The app does not set them to a variable and then call that variable the way I had to when I was working in the console.
It just invokes the bound functions directly as soon as an event occurs on one of the jQuery elements. But I thought writing it this way would just return a copy of the function, and not run the function itself, if I am basing my assumptions on what I have figured out in the code I wrote above. I thought in order to invoke the function immediately, you would need to use call or apply.
I also realize that the app runs the bindEvents method when it starts (see line 46). So I understand that when you start the app, copies of the various functions are created with the correct 'this' bound to the functions. But...when/how do they actually get invoked without assigning them to variables? How are these copies accessed?
I think I have a flawed understanding of the bind method, so I would love some help. Thanks!
It sounds like you understand bind well enough. Perhaps there is some confusion with passing anonymous functions. As you know calling bind returns a new function and this can optionally be stored as a variable or passed as a function argument.
In the example below btn1 accepts a bound function as you've seen. This could also be written in a more long hand fashion with btn2. They're identical. btn3 doesn't receive a bound function, when its clicked its context is the button element, this looses all visibility of MagicalApp fucntions.
<button id="example1">button one bound</button>
<button id="example2">button one bound</button>
<button id="example3">button two unbound</button>
<script>
class MagicalApp {
add() {
console.log('this could do addition');
}
}
const app = new MagicalApp();
function contextOfEvent(event) {
console.log('contextSensitive', this.add)
}
const btn1 = document.querySelector("#example1");
btn1.addEventListener('click', contextOfEvent.bind(app));
const btn2 = document.querySelector("#example2");
const btn2ClickHandler = contextOfEvent.bind(app)
btn2.addEventListener('click', btn2ClickHandler);
const btn3 = document.querySelector("#example3");
btn3.addEventListener('click', contextOfEvent);
</script>

pass arguments inside button onclick function inside bindPopUp in leaflet

I am trying to create a button listener function inside bindPop in leaflet. But it does not read parameter of onclick function. In the below code alertConfirmed()function works fine for me but filterEventsBasedOnCluster(feature) does not read the parameter 'feature'. It says feature is not defined. feature is an object.
here is the code:
layer.bindPopup('<div id="alert">Found...!<input type="button" value="Please confirm" onclick="alertConfirmed()"> <input type="button" id="create" value="see patients" onclick="filterEventsBasedOnCluster(feature)"><table id="table"></table></div>')
`
Any help is much appreciated.
If you attach event handlers via the onclick HTML attribute, you can not control the parameters received by that handler. Let me quote the docs:
The single argument passed to the specified event handler function is a MouseEvent object. Within the handler, this will be the element upon which the event was triggered.
The way to pass a custom argument is to define a closure, by having a function that returns a function that receives only the event reference.
This is exactly the same solution as described in «Leaflet.contextmenu callbacks» and «Leaflet marker event fires at wrong time».
Read that. I mean it.
So in the end it should look something like:
function getHandlerForFeature(feat) { // A function...
return function(ev) { // ...that returns a function...
console.log(feat); // ...that has a closure over the value.
}
}
layer.bindPopup("<button id='mybutton'>Foo!</button>")
// The button doesn't exist in the DOM until the popup has been opened, so
layer.on('popupopen', function(){
L.DomEvent.on(
document.getElementById('mybutton'),
'click',
getHandlerForFeature(layer) // The result of this call is the event handler func.
);
});
Note that you can not use the onclick="code" syntax, as you need to create a string of runnable code, and that code will only be able to access variables in the global scope. Sure, you can JSON.stringify() your data, but you won't be able to have references to variables outside.
try this:
I am just correcting the wrong part only:
onclick="filterEventsBasedOnCluster('+feature+')"
You are not passing the variable properly.

jQuery `this` scope issue

I have a global function defined in one place:
function addToCart (){
var prodText = $(this).parent().siblings(".item1").text();
$("#"+prodId+"shopC").children(".item1").text(prodText);
alert(prodText);
}
Then, I want to call it inside a HTML element with an inline onClick event:
onClick='addToCart()'
It is not working, but it works if I put the function code directly inside the onClick event, so that must be a this scope issue.
There are many questions/explanations about this scope but I must confess I miss a simple straight answer for this specific case (I tried to use "use strict" with success either).
How to make this work?
As per current implementation this doesn't refers to the element which invoked the function. It refers to window object.
You need to pass the current element context i.e. this to the function as
onClick='addToCart(this)'
and modify the function to accept element as parameter.
function addToCart (elem){
var prodText = $(elem).parent().siblings(".item1").text();
$("#"+prodId+"shopC").children(".item1").text(prodText);
alert(prodText);
}
Basically this inside a plain function will point to window. you have to pass the this context to the inline handler onClick='addToCart(this)'. Receive it and use it inside of event handler like below.
function addToCart (_this){
var prodText = $(_this).parent().siblings(".item1").text();
you have to pass this keyword where you inline calling the addToCart function then you can capture that element
onClick='addToCart(this)'
this object in your function does not point to the object where you added the onClick function to. It rather points to the window object.
You need to pass this as a param to your function.
function addToCart (trigger) { // Code goes here }
and call addToCart(this) in your onClick.
Learn more about this in javascript here.

Can a click handler be an object?

I'm trying to register on +1 clicks from within my module, which is wrapped as an annonymous function.
For this end, I created a global object MyModule, and exported my click handler function through it. The problem is - my click handler doesn't get called.
Live demo. Code:
// Initialize +1 button
gapi.plusone.go();
(function(){
window.MyModule = {};
function plusOneClicked() {
alert("+1!");
}
window.MyModule.plusOneClicked = plusOneClicked;
})()
...
<g:plusone callback='window.MyModule.plusOneClicked'></g:plusone>
When I give as a callback an external function, whose only purpose is to forward the calls to window.MyModule.plusOneClicked, it works:
function foo() {
window.MyModule.plusOneClicked();
}
...
<g:plusone callback='foo'></g:plusone>
Why would the click handler miss window.MyModule.plusOneClicked(), but find foo()?
Google is probably writing
window[callback]();
in their code.
This requires that the callback string refer to a property of window, not a property of another object.
I believe because callback expects a direct handler method (as in foo()) rather than a reference (as in window.MyModule.plusOneClicked). So basically, you cannot simply assign such a reference to click handler, but write a (wrapper) method as the handler and have it perform the necessary invocation.

Categories

Resources