'this.function' is not a function - OO JS - javascript

I have a modal object that has various functions as its properties, but when I click to open a modal I'm getting the error this.openModal is not a function. I've tried debugging but it just falls over as soon as it hits the function I want it to run. I suspect it might be an issue with the 'this' binding, but I'm not sure where the problem is. All my JS is below, one function kind of chains onto another so it's easier to see the whole object.
var modal = function () {
// Modal Close Listeners
this.closeModalListen = function(button) {
var modalFooter = button.parentElement;
var modalContent = modalFooter.parentElement;
var modalElement = modalContent.parentElement;
var backdrop = document.getElementById("modal-backdrop");
this.closeModal(modalElement, backdrop);
}
// Open Modal
this.openModal = function(button) {
var button = button;
var modal = button.getAttribute("data-modal");
var modalElement = document.getElementById(modal);
var backdrop = document.createElement('div');
backdrop.id="modal-backdrop";
backdrop.classList.add("modal-backdrop");
document.body.appendChild(backdrop);
var backdrop = document.getElementById("modal-backdrop");
backdrop.className += " modal-open";
modalElement.className += " modal-open";
}
// Close Modal
this.closeModal = function(modalElement, backdrop) {
modalElement.className = modalElement.className.replace(/\bmodal-open\b/, '');
backdrop.className = backdrop.className.replace(/\bmodal-open\b/, '');
}
// Initialise Function
this.init = function () {
// Create Events for creating the modals
if (document.addEventListener) {
document.addEventListener("click", this.handleClick, false);
}
else if (document.attachEvent) {
document.attachEvent("onclick", this.handleClick);
}
}
// Handle Button Click
this.handleClick = function(event) {
var thisModal = this;
event = event || window.event;
event.target = event.target || event.srcElement;
var element = event.target;
while (element) {
if (element.nodeName === "BUTTON" && /akela/.test(element.className)) {
thisModal.openModal(element);
break;
} else if (element.nodeName === "BUTTON" && /close/.test(element.className)) {
thisModal.closeModalListen(element);
break;
} else if (element.nodeName === "DIV" && /close/.test(element.className)) {
thisModal.closeModalListen(element);
break;
}
element = element.parentNode;
}
}
}
// Initalise Modal Engine
var akelaModel = new modal();
akelaModel.init();
I'm looking to fix this with pure js and no jquery.

You need to bind the function to the object before giving it as a event listener:
document.addEventListener("click", this.handleClick.bind(this), false);
document.attachEvent("onclick", this.handleClick.bind(this));
Otherwise it becomes detached from its original object and doesn't have the expected this.

As an alternative to using bind, you can move:
var thisModal = this;
from the handleClick method to the constructor.
Also, it's convention to give constructors names starting with a capital letter so it's easier to see that they're constructors.
var Modal = function () {
var thisModal = this;
// Open Modal
this.openModal = function(button) {
console.log('openModal called on ' + button.tagName);
}
// Initialise Function
this.init = function () {
// Create Events for creating the modals
if (document.addEventListener) {
document.addEventListener("click", this.handleClick, false);
}
}
// Handle Button Click
this.handleClick = function(event) {
thisModal.openModal(event.target);
}
}
// Initalise Modal Engine
var akelaModel = new Modal();
akelaModel.init();
<div>Click <span>anywhere</span></div>

Related

How to trigger a function with multiple Event Handler (change)

I would like to add the condition, that the function is only triggered if both
addEventListener('change', SwitchG) Events are True (=both have changed).
The code which I use currently activates the function already when one of the two has changed.
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG () {
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
You need another variable, which checks if both have been changed and only executes the handler function if both changes already happened:
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
var countChanges = 0; // <-- this tracks changes
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG () {
countChanges += 1; // <-- count up
if (countChanges >= 2) {
countChanges = 0; // <-- reset (if needed)
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
}
A more robust implementation however, also tracks the elements which changed and ensures a repeating change event from a single element won't succeed to run the handler.
For example with this utility:
function ChangedCounter (minChanges) {
var elements = new Set();
return {
changed(element) {
elements.add(element);
},
clear() {
elements.clear();
},
isReady() {
return elements.size >= minChanges;
}
};
}
You'd write it like this:
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
var countChanges = ChangedCounter(2);
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG (e) {
countChanges.changed(e.target);
if (countChanges.isReady()) {
countChanges.clear();
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
}
You could create a "state" to store when the both has changed. I've created two variables, halloState and hallo1State. The snippet below shows how it could be done:
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
var halloState = false;
var hallo1State = false;
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG (e) {
if(e.target.id === "S131_01") halloState = true;
else if(e.target.id === "S130_01") hallo1State = true;
if(halloState && hallo1State){
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
}
.css {
background-color:red;
}
<input id="S131_01" type="text"/>
<input id="S130_01" type="text"/>
<button id="submit">Submit</button>

Event Listener on images ignored within modal window

I'm stuck as to why I can't get an AddEventListener click event to work on a set of images that appear in a modal. I had them working before before the modal aspect was involve, but I'm not sure that the modal broke the image click event either.
Here is the function in question, which is called within a massive document.addEventListener("DOMContentLoaded", function (event) function:
var attachClick = function () {
Array.prototype.forEach.call(containers, function (n, i) {
n.addEventListener('click', function (e) {
// populate
cleanDrawer();
var mediaFilterSelected = document.querySelector('.media-tags .tag-container .selected');
var selectedFilters = "";
if (mediaFilterSelected != "" && mediaFilterSelected != null) {
selectedFilters = mediaFilterSelected.innerHTML;
}
var portfolioItemName = '';
var selectedID = this.getAttribute('data-portfolio-item-id');
var data = portfolioItems.filter(function (item) {
portfolioItemName = item.name;
return item.id === selectedID;
})[0];
clientNameContainer.innerHTML = data.name;
descriptionContainer.innerHTML = data.description;
var childItems = data.child_items;
//We will group the child items by media tag and target the unique instance from each group to get the right main banner
Array.prototype.groupBy = function (prop) {
return this.reduce(function (groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var byTag = childItems.groupBy('media_tags');
if (childItems.length > 0) {
handleBannerItem(childItems[0]);
var byTagValues = Object.values(byTag);
byTagValues.forEach(function (tagValue) {
for (var t = 0; t < tagValue.length; t++) {
if (tagValue[t].media_tags == selectedFilters) {
handleBannerItem(tagValue[0]);
}
}
});
childItems.forEach(function (item, i) {
// console.log("childItems.forEach"); we get into here
var img = document.createElement('img'),
container = document.createElement('div'),
label = document.createElement('p');
container.appendChild(img);
var mediaTags = item.media_tags;
container.className = "thumb";
label.className = "childLabelInactive thumbLbl";
thumbsContainer.appendChild(container);
if (selectedFilters.length > 0 && mediaTags.length > 0) {
for (var x = 0; x < mediaTags.length; x++) {
if (mediaTags[x] == selectedFilters) {
container.className = "thumb active";
label.className = "childLabel thumbLbl";
}
}
}
else {
container.className = i == 0 ? "thumb active" : "thumb";
// console.log("no tags selected"); we get to here
}
img.src = item.thumb;
if (item.media_tags != 0 && item.media_tags != null) {
childMediaTags = item.media_tags;
childMediaTags.forEach(function (cMTag) {
varLabelTxt = document.createTextNode(cMTag);
container.appendChild(label);
label.appendChild(varLabelTxt);
});
}
//console.log("before adding click to images"); we get here
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
});
}
attachClick();
//open a modal to show off the portfolio pieces for the selected client
var tingleModal = document.querySelector('.tingle-modal');
drawer.className = 'drawer';
var portfolioModal = new tingle.modal({
onOpen: function() {
if(tingleModal){
tingleModal.remove();
}
console.log('modal open');
},
onClose: function() {
console.log('modal closed');
//tingleModal.remove();
}
});
e.preventDefault();
portfolioModal.open();
portfolioModal.setContent(document.querySelector('.drawer-content').innerHTML);
});
});
};
And the specific bit that I'm having trouble with:
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
I tried removing the e.PreventDefault() bit but that didn't solve the issue. I know the images are being created, so the img variable isn't empty. I feel like the addEventListener is setup correctly. I also tried moving that bit up just under the img.src = item.thumb line, but no luck. For Some reason, the click event just will not trigger for the images.
So if I understand correctly, you have a modal that lies above the images (it has a higher z-index)? Well in this case the clicks are not reaching the images as they will hit the modal. You can pass clicks through elements that lie above by applying the css property pointer-events: none; to the modal, but thats somehow controversial to what a modal is intended to do.
Are the images present in the modal on DOMContentLoaded? You may be able to try delegating the handling of clicks to a parent element if that's the case.
You can try the delegation approach shown here: Vanilla JavaScript Event Delegation

Javascript calling other function without reason

I want to attach an event to a button and if user clicks, an alert should appear. But here, even if the user doesnt click, the alert appears.
Js File :
var init = function (m) {
_m = m;
var actionButton = document.getElementById("action");
if (actionButton) {
var buttonId = "action";
if (actionButton.attachEvent) {
actionButton.attachEvent("onclick", _onActionClick(buttonId));
}
}
var _onActionClick = function (buttonId) {
alert("3");
}
Here, I get alert 3.
But, with this code, I do not get alert 3.
var init = function (m) {
_m = m;
var actionButton = document.getElementById("action");
if (actionButton) {
var buttonId = "action";
if (actionButton.attachEvent) {
actionButton.attachEvent("onclick", _onActionClick);
}
}
var _onActionClick = function (){
alert("3");
}
Can someone, let me know where am I going wrong ?
onclick needs a function. You're using the return value of _onActionClick(buttonId) which is undefined
// no good!
actionButton.attachEvent("onclick", _onActionClick(buttonId));
Try using an actual function
actionButton.attachEvent("onclick", function(event) {
_onActionClick(buttonId)
})
Or you can define _onActionClick in curried form
var _onActionClick = function(buttonId) {
return function(event) {
console.log(buttonId, event)
}
}
// now when you call _onActionClick(buttonId) it will return a function ...
actionButton.attachEvent("onclick", _onActionClick("action"))

ng-click firing when selecting text or dragging

When using ng-click on a div:
<div ng-click="doSomething()">bla bla</div>
ng-click fires even if the user only selects or drags the div. How do I prevent that, while still enabling text selection?
In requiring something similar, where the usual text selection behavior is required on an element which should otherwise respond to ngClick, I wrote the following directive, which may be of use:
.directive('selectableText', function($window, $timeout) {
var i = 0;
return {
restrict: 'A',
priority: 1,
compile: function (tElem, tAttrs) {
var fn = '$$clickOnNoSelect' + i++,
_ngClick = tAttrs.ngClick;
tAttrs.ngClick = fn + '($event)';
return function(scope) {
var lastAnchorOffset, lastFocusOffset, timer;
scope[fn] = function(event) {
var selection = $window.getSelection(),
anchorOffset = selection.anchorOffset,
focusOffset = selection.focusOffset;
if(focusOffset - anchorOffset !== 0) {
if(!(lastAnchorOffset === anchorOffset && lastFocusOffset === focusOffset)) {
lastAnchorOffset = anchorOffset;
lastFocusOffset = focusOffset;
if(timer) {
$timeout.cancel(timer);
timer = null;
}
return;
}
}
lastAnchorOffset = null;
lastFocusOffset = null;
// delay invoking click so as to watch for user double-clicking
// to select words
timer = $timeout(function() {
scope.$eval(_ngClick, {$event: event});
timer = null;
}, 250);
};
};
}
};
});
Plunker: http://plnkr.co/edit/kkfXfiLvGXqNYs3N6fTz?p=preview
I had to deal with this, too, and came up with something much simpler. Basically you store the x-position on mousedown and then compare new x-position on mouseup:
ng-mousedown="setCurrentPos($event)"
ng-mouseup="doStuff($event)"
Function setCurrentPos():
var setCurrentPos = function($event) {
$scope.currentPos = $event.offsetX;
}
Function doStuff():
var doStuff = function ($event) {
if ($event.offsetX == $scope.currentPos) {
// Only do stuff here, when mouse was NOT dragged
} else {
// Do other stuff, which includes mouse dragging
}
}

Javascript, problem with binding an event to a div-tag

i am trying to bind an event to a dynamically created div.
function GameField(playerNumber) {
this.fields = new Array();
this.player = playerNumber;
this.isPlayerActive = false;
this.currentRound = 0;
}
GameField.prototype.InitField = function(fieldNumber) {
var newField = document.createElement("div");
if (fieldNumber == 0 || fieldNumber == 6 || fieldNumber == 8 || fieldNumber == 17)
newField.className = 'gameCellSmall borderFull gameText gameTextAlign';
else
newField.className = 'gameCellSmall borderWithoutTop gameText gameTextAlign';
newField.onclick = function() { this.DivClick('a'); }
this.fields[fieldNumber] = newField;
return newField;
}
GameField.prototype.DivClick = function(fieldNumber) {
alert('Nummer: ' + fieldNumber);
}
Everything works perfectly, but when you click on one of the created divs, i end up with the following error message: Error: Object doesn't support this property or method.
If i replace the onclick function with this, then it works:
newField.onclick = function() { alert('Nummer: ' + fieldNumber); }
How can i get the onclick event to fire my DivClick function instead?
The problem is that the onclick event handler gets executed with the this value pointing to the DOM element that triggered the event, so that's why executing this.DivClick fails.
You need to enforce the context, in order to use instance methods within the event handler, for example, you could store a reference to the current instance:
GameField.prototype.InitField = function(fieldNumber) {
var newField = document.createElement("div");
//...
var instance = this;
newField.onclick = function() { instance.DivClick('a'); }
//...
}
That is the way
function DivClick (fieldNumber) {
alert('Nummer: ' + fieldNumber);
}
{ this.DivClick('a'); } - should be replaced to { DivClick('a'); }

Categories