JS Controller call parent in callback? - javascript

I have a controller that is extended by a a childcontroller. This child needs needs to display an element first and after that raise the overriden parent function. Here is my abstracted code:
Ext.define('ParentController', {
extend: 'Ext.app.Controller',
//lot of code
myFunction(){
//....
this.getSomething();
}
}
and then there is a controller extending this existing one:
Ext.define('ChildController', {
extend: ParentController,
onlyChildFunction(dummy){
//create element
...
element.onClosed = function(){
dummy();
}
return element;
}
//override
myFunction(){
//this.callParent();
var element = onlyChildFunction( this.self.superclass.myFunction() );
element.show();
}
Passing the superclass function doesn't work because the ParentController is using a lot of references to a instance of ParentController (this).
I don't want to copy the code from ParentController directly, because it would mean to maintain the same function twice. One way could be to call myFunction() on element.onClosed again and make some kind of flag there only to do a callParent(). But this sounds ugly - any better suggestions?
Thanks in advance - help is appreciated!

If I understand correctly, onlyChildFunction must be passed a Function. (Here, you are passing the return value of calling the parent class's myFunction.)
Would something like this work ?
Ext.define("ChildController", {
...
myFunction : function () {
var that = this;
var element = onlyChildFunction( function () {
that.self.superclass.myFunction()
});
...
}
}
The idea being that you pass a function that calls the "parent" function in the right context.
In which case, you might be able to use the bind function to the same effect :
var element = onlyChildFunction(this.self.superclass.myFunction.bind(this));
But I'm not sure what the this / self / superclass values are in your case...

Related

jQuery $(this) not working when inside a function

I have this simple function that copies some html, and places it in another div.
If I put the code for the function in the click event it works fine, but when I move it into a function (to be used in multiple places) it no longer works.
Do you know why this is?
If I console.log($(this)); in the function it returns the window element.
function addHTMLtoComponent () {
var wrapper = $(this).closest(".wrapper");
var component = $(wrapper).find(".component");
var componentCodeHolder = $(wrapper).find('.target');
$(componentCodeHolder).text(component.html())
//console.log($(this));
}
$(".js_show_html").click(function () {
addHTMLtoComponent();
});
codepen here - http://codepen.io/ashconnolly/pen/ebe7a5a45f2c5bbe58734411b03e180e
Should i be referencing $(this) in a different way?
Regarding other answers, i need to put the easiest one:
$(".js_show_html").click(addHTMLtoComponent);
since you called the function manually the function doesn't know the "this" context, therefore it reverted back to use the window object.
$(".js_show_html").click(function () {
addHTMLtoComponent();
});
// Change to this
$(".js_show_html").click(function () {
// the call function allows you to call the function with the specific context
addHTMLtoComponent.call(this);
});
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
this in the context of the click() event is the element clicked. In the context of the function addHTMLtoComponent this no longer is a reference to the element clicked.
Try passing the clicked object to the function to maintain the object reference.
function addHTMLtoComponent ($obj) {
var $wrapper = $obj.closest(".wrapper");
var $component = $wrapper.find(".component");
var $componentCodeHolder = $wrapper.find('.target');
$componentCodeHolder.text($component.html());
}
$(".js_show_html").click(function () {
addHTMLtoComponent($(this));
});
The special keyword this, when you call a function by itself, is the window object (which is what you observed). For the behavior you need, just add a parameter to the function that loads the appropriate context:
function addHTMLtoComponent(context) {
var wrapper = $(context).closest(".wrapper");
var component = $(wrapper).find(".component");
var componentCodeHolder = $(wrapper).find('.target');
$(componentCodeHolder).text(component.html())
//console.log($(context));
}
$(".js_show_html").click(function() {
addHTMLtoComponent(this);
});
One thing you could consider is that addHTMLtoComponent() could be made into a jQuery function itself:
$.fn.addHTMLtoComponent = function() {
return this.each(function() {
var wrapper = $(this).closest(".wrapper");
var component = $(wrapper).find(".component");
var componentCodeHolder = $(wrapper).find('.target');
componentCodeHolder.text(component.html())
});
}
Now you can call it like any other jQuery method:
$(".js_show_html").click(function () {
$(this).addHTMLtoComponent();
});
The value of this in a jQuery method will be the jQuery object itself, so you don't need to re-wrap it with $(). By convention (and when it makes sense), jQuery methods operate on all elements referred to by the root object, and they return that object for further chained operations. That's what the outer return this.each() construction does.
Inside the .each() callback, you've got a typical jQuery callback situation, with this being set successively to each member of the outer jQuery object.
You have to pass the element as parameter to this function.
eg:
<div onclick="addHTMLtoComponent ($(this))"></div>

Calling a custom function in JQuery

I want to call a JavaScript function that I made after a JQuery event has been called. I defined a function called scrambleDot earlier like this var scrambleDot = new function()
{ //my code }. Here's the code that I tried to use:
$('#reveal').click(function() {
$('.cover').css({'visibility':'hidden'});
$('#under').css({'visibility':'visible'});
})
$('#conceal').click(function() {
$('scrambleDot');
})
})
You have to call it just like:
scrambleDot();
To define a function, you don't need the new operator, so you should have:
var scrambleDot = function() { //my code }
If it still throws an error, it means it was defined in other scope. To make it globally accesible, do this when defining it:
window.scrambleDot = function() { //my code }
Cheers
We have to use new keyword, only when the function is used as a constructor for new Objects. So, the definition should not use new.
var scrambleDot = function() { //my code }
If the function need not be created dynamically, I would recommend
function scrambleDot() {
...
}
To invoke the function, simply do
scrambleDot();
For that call the function instead of selecting an element as:
$('#reveal').click(function() {
$('.cover').css({'visibility':'hidden'});
$('#under').css({'visibility':'visible'});
})
$('#conceal').click(function() {
scrambleDot();
});
And also, you write functions as:
function scrambleDot () {
// your code
}
It is a better practice than the variable one.

Confused by this - getting error "this.myfuntion() is not a function"

Background: I am trying to edit a zen cart horizontal pop out menu to make the popout open inline within the menu. The problem I am having is that I am struggling to get my head around the javascript/jquery that came with it.
Without posting the whole thing the structure of the code is something like this:
(declare some vars)
//some functions like this:
function funcname(obj) {
//do something
}
//then one big master function like this:
function bigfunc(arg1, arg2, arg3, arg4, arg5) {
//declare some vars based on this
this.varname1=varname1;
this.varname2=varname2;
//declare some functions inside the big function
this.innerfunc1= function() {
//do stuff
}
this.innerfunc2= function() {
//do stuff
}
}//end of big function
//then goes on to declare init function
function initfunc(){
//this creates new bigfunc(arg1 arg2 arg3...) for each main menu item
}
//finally calls init function with
window.onload = initfunc();
Now on to my confusion -
1) firstly for clarification, am I correct in thinking based on all the this's floating about in bigfunc() and the fact that it is called with new bigfunc() that this is creating an object?
2)My current problem is with one of the functions inside bigfunc() which looks like this:
this.slideChildMenu = function() {
var divref = this.children[0].div;
var ulref = this.children[0].ul;
var maxwidth = this.children[0].width;
var nextWidth;
if (this.isMouseOnMe || this.isMouseOnChild()) {
nextWidth = divref.offsetWidth + slideSpeed_out;
if (nextWidth >= maxwidth) {
this.finishOpeningChild(divref, ulref, maxwidth);
} else {
ulref.style.left = nextWidth - maxwidth + "px";
divref.style.width = nextWidth + "px";
setTimeout("slideChildMenu('" + this.getId() + "')", slideTimeout_out);
}
}
Now my plan is to alter this to use jquery show to open the element so I tried this:
this.slideChildMenu = function() {
var divref = this.children[0].div;
var ulref = this.children[0].ul;
if (this.isMouseOnMe || this.isMouseOnChild()) {
$(divref).show(function(){
this.finishOpeningChild(divref, ulref);
});
}
}
But I am getting this-> TypeError: this.finishOpeningChild is not a function
Now, there is a lot of other stuff going on in this js so I wouldnt dream of asking someone on here to do my work for me, but I am hoping that if someone can explain to me why this function is not a function I may be able to work the rest out.
NOTE: I thought this was to do with the scope of "this" but the value of this appears to be exactly the same in both versions of the code.
I know this is a long one but your help is greatly appreciated.
The value of this in a function is called the "context" in which the function runs. In general, whenever you pass a callback function as an argument (as you do with $(divref).show(function() {...})), the function can run the callback in whatever context it wants. In this case, the jQuery show function chooses to run its callback in the context of the element being animated.
However, you want access to the value of this at the time the anonymous callback function is defined, rather than when it is run. The solution here is to store the outer value of this in a variable (traditionally called self) which is included in the scope of the newly-defined function:
this.slideChildMenu = function() {
//...
var self = this;
$(divref).show(function(){
self.finishOpeningChild(divref, ulref);
});
}
I am thinking that the jQuery selector has changed the scope of this.
In your example $(this); would refer to object being animated per jQuery api docs:
If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.
If the object in question is instantiated you can call it with dot notation without using this like bigFunc.finishOpeningChild(divref, ulref);
You're probably a little confused about scope, it's not always easy keeping track, but doing something more like this:
var site = {
init: function(elm) {
self=site;
self.master.funcname2(self.varname1, elm); //call function in master
},
funcname: function(obj) {
//do something
},
varname1: 'some string',
varname2: 3+4,
master: function() {
this.varname3 = sin(30);
this.funcname2 = function(stuff, element) {
site.funcname(element); //call function in 'site'
var sinus = site.master.varname3; //get variable
}
}
}
window.onload = function() {
var elm = document.getElementById('elementID');
site.init(elm); //call init function
}
usually makes it a little easier to keep track.

How to pass parameters to a function declared like left = function()

How can I pass parameters to a function declared like something = function(){};
window.prototype.initInterface = function(){
this.mainPane = document.createElement('div');
this.mainPane.style.border="5px solid grey";
this.mainPane.style.margin="0px";
this.mainPane.style.width="420px";
this.mainPane.style.height="600px";
this.exitButton = document.createElement('input');
this.exitButton.setAttribute("type", "button");
this.exitButton.setAttribute("value", "exit");
this.exitButton.onclick = function(){
document.body.removeChild(this.mainPane);
};
this.mainPane.appendChild(this.exitButton);
document.body.appendChild(this.mainPane);
}
When the user presses the exit button I want to remove the mainPane from the body of the html page.
this.exitButton.onclick = function(this.mainPage){
document.body.removeChild(this.mainPane);
};
Does not work
How can I do this?
For your exitButton.onclick function to have access to variables you create in the enveloping initInterface function you want a to create a closure in the exitButton.onclick function by returning a function that performs the action you want and passing that the variable.
exitButton.onclick = function () {
return (function() {
document.body.removeChild(mainPane);
})(mainPane);
};
Read more on how closures work here and here and see a working example fiddle.
Alternatively, you forget about closures and walk up the DOM from the button which triggers the event to your mainPane
exitButton.onclick = function() {
// in here "this" is the object that triggered the event, exitButton
document.body.removeChild(this.parentNode);
}
As an aside, window.prototype does not exist if you are doing this in a browser; window is the object at the top of prototype chain in browser scripting. You want just window.initInterface = function () {} which is the exact same thing as function initInterface() {} because everything you do in javascript in the browser becomes a property of window.
This function is the function w/o function name. It could only be used once and you may not easy to find out what parameters should be passed.
You can create another function like :
function go(a1){}
And call it like window.prototype.initInterface = go(a1);
Or you can get some DOM parameters in this unnamed function by using functions like getDocumentById("DOM ID") etc.

JavaScript "this" references the wrong object within an event handler

I'm writing some MVC JavaScript code using Prototype. The problem is that when I reference this in the snippet below it does of course reference the Window object, whereas I need it to refer to my Controller instance so it can invoke my updateValue function, passing the HTML element ID.
I think I have to use bind or bindAsEventListener but I don't really understand how.
var Foo = {
Controller: Class.create({
observeEvents: function() {
$$("#myform input").each(function(input) {
input.observe("blur", this.updateValue(input.id); // <- wrong this!
});
},
updateValue: function(elementID) {
...
}
})
}
Any help would be much appreciated.
This should work.
observeEvents: function() {
var Controller = this;
$$("#myform input").each(function(input) {
input.observe("blur", Controller.updateValue.bind(Controller, input.id));
});
...
If you don't ever want to learn how to use bind (and frankly I don't blame you) then you can forget about it and just use another teensy closure.
observeEvents: function() {
var Controller = this;
$$("#myform input").each(function(input) {
input.observe("blur", function(event) {
Controller.updateValue(input.id);
});
});
...

Categories

Resources