Javascript functions in associative array "is not a function" - javascript

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?

Related

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>

JS: call methods of an object inside jquery "click"

I have a fundamental misunderstanding of one of my numerous errors. I use jquery.
I have an object defined as:
var terms = {};
terms.clear_history = function(a, b)
{ /* DO SOMETHING */ }
I can call the terms.clear_history(1,2) function in my main js file, no problem. But when I try to call it from the "click" of a <a/> element:
$(document).on('click', '#clearterms', function(){
terms.clear_history(1, 2);
});
it gives me the following error:
Uncaught TypeError: Object # has no method 'clear_history'
I understand that I don't understand something fundamental here...
Thank you!
It sounds like a scope issue. Maybe the terms in the global scope the same as the one assigned clear_history given the method.
also, you don't want to name your param as this which is a reserved keyword in JS.
try this:
window.terms = {};
window.terms.clear_history = function(foo,bar){console.log(foo,bar);};
//then later:
$(document).on('click', '#clearterms', function(){
window.terms.clear_history(1, 2);
});

Access parent property inside object literal

We have a JS framework that lets us set up "modules". Each module is added by calling the addModule method and passing a literal object that contains required properties about the module as well as optional methods. Example:
framework.addModule({
id: "test-module",
init: function () {
//stuff to do when initializing like set up jQuery bindings
$("div").click(function () {
// need access to literal object so I can call:
something.utility1();
});
},
utility1: function () {
something.utility2();
},
utility2: function () {
// need access to literal object so I can call:
}
});
I'm trying to figure out the easiest way to make the object itself available to any code, at any level, inside the object (in place of "something").
The best I've been able to do is to add a this: this property to the object and then inside of methods I can put var module = this, which works but requires that variable to be added to each module. I'd like to see if there's another way that wouldn't require adding a variable to each method. Thanks.
Thanks for the comments and, zzzzBov, thanks for your suggestions.
However, it looks like the below code will work best for my needs. The devs on my team are writing a lot of these modules and I need the solution to be clear to them. Having to call $.proxy could make it less clear. I was hoping to avoid having to put var module = this in each method, so it would be cleaner, but it seems that it's not possible without it.
framework.addModule({
id: "test-module",
init: function () {
var module = this;
$("div").click(function () {
module.utility1();
});
},
utility1: function () {
var module = this;
module.utility2();
},
utility2: function () {
}
});
If anyone has a cleaner solution, let me know.
jQuery has a proxy method which will bind the function to a specific context. This would turn your event binding into:
$('div').click($.proxy(this, 'utility1'));
Alternatively, instead of using an object literal to instantiate the module object, you could instantiate an anonymous function:
framework.addModule(new function () {
this.id = 'test-module';
this.init = function () {
$('div').click($.proxy(this, 'utility1'));
};
this.utility1 = function () {
...more code...
};
this.utility2 = this.utility1;
});

jQuery animate callback + Backbone: Cannot call method 'remove' of undefined

I'm not a newbie to JavaScript, but often I find its flexible ways (like defining anonymous function as callbacks and their scope) quite confusing. One thing I'm still struggling with are closures and scopes.
Take this example (from a Backbone model):
'handleRemove': function() {
var thisModel = this;
this.view.$el.slideUp(400, function() { thisModel.view.remove(); });
},
After the model is removed/deleted, this will animate its view and finally remove it from the DOM. This works just fine - but initially I tried the following code:
'handleRemove': function() {
var thisModel = this;
this.view.$el.slideUp(400, thisModel.view.remove );
},
Which is basically the same, but without the function() {} wrapper for the remove() call.
Can someone explain why the latter code does not work? I get the following exception/backtrace:
Uncaught TypeError: Cannot call method 'remove' of undefined backbone-min.js:1272
_.extend.remove backbone-min.js:1272
jQuery.speed.opt.complete jquery-1.8.3.js:9154
jQuery.Callbacks.fire jquery-1.8.3.js:974
jQuery.Callbacks.self.fireWith jquery-1.8.3.js:1084
tick jquery-1.8.3.js:8653
jQuery.fx.tick
Thank you!
That's because the context (this) of the callback function changes to the element being animated by jQuery.
var obj = { fn: function() { // Used as below, the following will print:
alert(this === obj); // false
alert(this.tagName); // "DIV"
}};
$('<div>').slideUp(400, obj.fn);
Furthermore, Backbone's view.remove function looks like this (source code):
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
Because this is not the Backbone view object any more, $el is not defined. Hence you get the "Cannot call method 'remove' of undefined" error.
Another way to avoid the error is to use Underscore's _.bind method:
this.view.$el.slideUp(400, _.bind(thisModel.view.remove, this) );

'this' not being set correct using jQuery and CoffeeScript

I am trying to write a rather simple "select all" feature, but I am getting errors with my javascript. The code is rather straight forward, so I'll just post it:
(function() {
$(function() {
var all_check_box;
all_check_box = '#tournament_league_127';
return $(all_check_box).change(function() {
return $('.leagueCheckBox').each(function() {
return this.prop("checked", true);
});
});
});
}).call(this);
This code was generated by the following CoffeeScript:
$ ->
all_check_box = '#tournament_league_127'
$(all_check_box).change ->
$('.leagueCheckBox').each ->
this.prop("checked", true)
However, when I click #tournament_league_127, I get the following error: this.prop is not a function. I'm not really sure what I'm doing wrong. Any help would be appreciated.
this refers to the element not the jQuery object so you need,
return $(this).prop("checked", true);
It should be $(this).prop ...(assuming jQuery 1.6+, before that .prop did not exist).

Categories