This keyword points to global object in class method? - class

I'm building a calculator using a class. Now I'm testing to see when i hit a number button that it will be displayed. It doesn't there is an error. Uncaught TypeError: Cannot set property 'innerText' of undefined.
Now when I remove the this keyword in the updateDisplay method everything works fine? As if the this keyword points to the global object? What is happening here?
const numberButtons = document.querySelectorAll('[data-number]');
const operationButtons = document.querySelectorAll('[data-operation]');
const equalsButton = document.querySelector('[data-equals]');
const deleteButton = document.querySelector('[data-delete]');
const allClearButton = document.querySelector('[data-all-clear]');
const previousOperandTextElement = document.querySelector('[data-previous-
operand]');
const currentOperandTextElement = document.querySelector('[data-current-
operand]');
class Calculator {
contructor(previousOperandTextElement, currentOperandTextElement) {
this.previousOperandTextElement = previousOperandTextElement;
this.currentOperandTextElement = currentOperandTextElement;
this.clear();
}
clear() {
this.currentOperand = '';
this.previousOperand = '';
this.operation = undefined;
}
delete(){
}
appendNumber(number) {
this.currentOperand = number;
}
chooseOperation(operation) {
}
compute() {
}
updateDisplay() {
this.currentOperandTextElement.innerText = this.currentOperand;
/* the code above throws an error, below works fine, so without the
this keyword? */
currentOperandTextElement.innerText = this.currentOperand;
}
}
const calculator = new Calculator(previousOperandTextElement,
currentOperandTextElement);
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.appendNumber(button.innerText)
calculator.updateDisplay();
})
})

Sorry, misspelled constructor.

Related

I cannot get the html doc to load the javascript to make my calculator working

I've followed this calculator video on YouTube. I have 3 files in a folder .html, .css & .js.
I open the calculator by double-clicking the HTML file which seems to load up fine in opera with the CSS changing the appearance, however the functionality of the buttons do not work at all. Now I have double-checked the code and even gone as far as cheating with the resource material to be sure it's not an error in the code. I feel that the JavaScript isn't being read/used at all when it loads up.
https://www.youtube.com/watch?v=j59qQ7YWLxw
class calculator {
constructor(perviousOperandTextElement, currentOperandTextElement) {
this.perviousOperandTextElement = perviousOperandTextElement
this.currentOperandTextElement = currentOperandTextElement
this.clear()
}
clear() {
this.currentOperand = ''
this.perviousOperand = ''
this.operation = undefined
}
delete() {
this.currentOperand = this.currentOperand.toString().slice(0, -1)
}
appendNumber(number) {
if (number === '.' && this.currentOperand.includes('.')) return
this.currentOperand = this.currentOperand.toString() + number.tostring()
}
chooseOperation(operation) {
if (this.currentOperand === '') return
if (this.perviousOperand !== '') {
this.compute()
}
this.operation = operation
this.perviousOperand = this.currentOperand
this.currentOperand = ''
}
compute() {
let computation
const prev = parseFloat(this.previousOperand)
const current = parseFloat(this.currentOperand)
if (isNaN(prev) || isNaN(current)) return
switch (this.operation) {
case'+':
computation = prev + current
break
case '-':
computation = prev - current
break
case '*':
computation = prev * current
break
case 'รท':
computation = prev / current
break
default:
return
}
this.currentOperand = computation
this.operation = undefined
this.perviousOperand = ''
}
getDisplayNumber(number) {
const stringNumber = number.toString()
const integerDigits = parseFloat(stringNumber.split('.')[0])
const decimalDigits = stringNumber.split('.')[1]
let integerDisplay
if (isNaN(integerDigits)) {
integerDisplay = ''
} else {
integerDisplay integerDigits.toLocaleString('en', { maximumFractionDigits: 0 })
}
if (decimalDigits != null) {
return `${integerDisplay}.${decimalDigits}`
} else {
return integerDisplay
}
}
updateDisplay() {
this.currentOperandTextElement.innerText =
this.getDisplayNumber(this.currentOperand)
if (this.operation != null) {
this.previousOperandTextElement.innerText =
`${this.getDisplayNumber(this.perviousOperand)} ${this.operation}`
} else {
this.previousOperandTextElement.innerText = ''
}
}
}
const numberButtons = document.querySelectorAll('[data-number]')
const operationButtons = document.querySelectorAll('[data-operation]')
const equalsButton = document.querySelector('[data-equals]')
const deleteButton = document.querySelector('[data-delete]')
const allClearButton = document.querySelector('[data-all-clear]')
const previousOperandTextElement = document.querySelector('[data-previous-operand]')
const currentOperandTextElement = document.querySelector('[data-current-operand]')
const calculator = new calculator(previousOperandTextElement, currentOperandTextElement)
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.appendNumber(button.innerText)
calculator.updateDisplay()
})
})
operationButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.chooseOperation(button.innerText)
calculator.updateDisplay()
})
})
equalsButton.addEventListener('click', button => {
calculator.compute()
calculator.updateDisplay()
})
allClearButton.addEventListener('click', button => {
calculator.clear()
calculator.updateDisplay()
})
deleteButton.addEventListener('click', button => {
calculator.delete()
calculator.updateDisplay()
})
Your javascript code is wrong at line 67.
We can see that at line 67, your code writes
integerDisplay integerDigits.toLocaleString('en', { maximumFractionDigits: 0 })
This is clearly wrong as you are missing a =, which assigns the value. A solution to this is to replace the line with
integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 })

How to simplify the search query parameter?

The problem
I have a movie database with the indexName: 'movies'.
Let's say my query is John then the domain is domain.tld/?movies[query]=John.
I want to simplify the search query parameter to domain.tld/?keywords=John. How can I do that?
What I already know
After reading through the docs I know that I have to modify the createURL and the parseURL somehow:
createURL({ qsModule, location, routeState }) {
const { origin, pathname, hash } = location;
const indexState = routeState['movies'] || {};
const queryString = qsModule.stringify(routeState);
if (!indexState.query) {
return `${origin}${pathname}${hash}`;
}
return `${origin}${pathname}?${queryString}${hash}`;
},
...
parseURL({ qsModule, location }) {
return qsModule.parse(location.search.slice(1));
},
After some try and error here is a solution:
createURL({ qsModule, location, routeState }) {
const { origin, pathname, hash } = location;
const indexState = routeState['movies'] || {}; // routeState[indexName]
//const queryString = qsModule.stringify(routeState); // default -> movies[query]
const queryString = 'keywords=' + encodeURIComponent(indexState.query); // NEW
if (!indexState.query) {
return `${origin}${pathname}${hash}`;
}
return `${origin}${pathname}?${queryString}${hash}`;
},
...
parseURL({ qsModule, location }) {
//return qsModule.parse(location.search.slice(1)); // default: e.g. movies%5Bquery%5D=john
const query = location.search.match(/=(.*)/g) || []; // NEW
const queryString = 'movies%5Bquery%5D' + query[0]; // NEW
return qsModule.parse(queryString); // NEW
},

Draft.js. How can I update block atomic:image src later on for example article save?

I am having trouble updating my image blocks in editorState in draft.js.
I want to change atomic:image src on button save.
So the src is for example now blob:http://localhost:3000/7661d307-871b-4039-b7dd-6efc2701b623
but I would like to update to src to for example /uploads-from-my-server/test.png
onSave(e) {
e.preventDefault();
const { editorState } = this.state;
const contentState = editorState.getCurrentContent();
editorState.getCurrentContent().getBlockMap().map((block) => {
const type = block.getType();
if (type === 'atomic:image') {
const rangeToReplace = new SelectionState({
anchorKey: block.getKey(),
focusKey: block.getKey(),
});
Modifier.replaceText(contentState, rangeToReplace, '/uploads-from-my-server/test.png');
const newContentState = editorState.getCurrentContent();
this.setState({ editorState: newContentState });
}
return true;
});
I know I can access src string with block.getData().get('src') but I cant set though
Thank you for your awesome editor
I was struggling with a similar problem, I ended up converting the content state to raw array using convertToRaw and then updating it manually and use convertFromRaw and set the new state :
import {EditorState, ContentState, convertToRaw, convertFromRaw /*, ...*/} from 'draft-js';
// ...
onSave(e) {
e.preventDefault();
const { editorState } = this.state;
const contentState = editorState.getCurrentContent();
let rawContent = convertToRaw(contentState);
for(let i = 0; i < rawContent.blocks.length; i++) {
let b = rawContent.blocks[i];
if(b['type'] !== "unstyled" && b.entityRanges.length === 1) {
const entityKey = b['entityRanges'][0]['key'];
const entityMap = rawContent['entityMap'][entityKey];
if(entityMap["type"] === "image") {
rawContent['entityMap'][entityKey]['data']['src'] = '/uploads-from-my-server/test.png';
}
}
}
const newContentState = convertFromRaw(rawContent);
const newEditorState = EditorState.push(this.state.editorState, newContentState, 'update-contentState');
this.setState({editorState: newEditorState});
}
Note: This is not a fully working example, it's just a starting point. Hope it helps :)

Cannot call method 'push' of undefined

I had this working in a fiddle just fine (which I can't find now), but when I moved it to VS2012 I'm getting the error "Cannot call method 'push' of undefined'.
In the code below, the createItemDiv() function works great and creates the UI elements. It's the line before that, showItem() which calls this.visibleItem.push() that is throwing the error. I had a problem with this in the fiddle originally and added the "this" to fix it. If I remove "this" as it is now, I get "visibleItem is not defined".
viewmodel.js
var dummyResults = [
{ //sample data is here }
]
var dummyItems = [
]
function VisibleItem(data) {
var self = this;
this.name = ko.observable(data.name);
this.type = ko.observable(data.type);
this.description = ko.observable("");
}
function SearchResult(data) {
var self = this;
this.name = ko.observable(data.name);
this.type = ko.observable(data.type);
}
var viewModel = {
searchResult: ko.observableArray(ko.utils.arrayMap(dummyResults, function (item) {
return new SearchResult(item);
})),
visibleItem: ko.observableArray(ko.utils.arrayMap(dummyItems, function (item) {
return new VisibleItem(item);
})),
showItem: function (item) {
this.visibleItem.push(item);
}
};
ko.applyBindings(viewModel);
site.js
$(document).on('click', '.result', function () {
var item = ko.dataFor(this);
viewModel.showItem(item); //add item to "visibleItems" viewmodel for management
createItemDiv(item); //ui function to show item on screen
});
try this :
var viewModel = function() {
var self = this;
self.searchResult = ko.observableArray(ko.utils.arrayMap(dummyResults, function (item) {
return new SearchResult(item);
})),
self.visibleItem = ko.observableArray(ko.utils.arrayMap(dummyItems, function (item) {
return new VisibleItem(item);
})),
self.showItem = function (item) {
self.visibleItem.push(item);
}
};
I just realized I had an old binding in my html still... will vote to close.

knockout viewmodel and requirejs

I have recently started to work with requirejs and when I try to create a simple viewmodel I get an strange exception. The exception comes from the knockout-2.1.0.js file and the exception is "Only subscribable things can act as dependencies".
define("PageViewModel", ["knockout-2.1.0"], function(ko) {
return function PageViewModel() {
var self = this;
self.visiblePage = ko.observable("StartPage");
self.showPage = function (pageName) {
self.visiblePage(pageName);
};
};
});
As you can see the viewmodel is extremly simple and since the error is in the knockout js file, it seems like requirejs is working as it should. I have been looking at: http://knockoutjs.com/documentation/amd-loading.html
The exception occur when coming to the line: self.visiblePage = ko.observable("StartPage");
Any ideas on what I'm doing wrong?
Thanks,
Ludwig
Update:
This is the module containing the pageviewmodel:
define("ViewModelFactory", ["StorageService", "PageViewModel", "AddUnitViewModel", "AddRoomViewModel"],
function (StorageService, PageViewModel, AddUnitViewModel, AddRoomViewModel) {
//var repositoryStorage = new StorageService();
var createAddRoomVM = function () {
var vm = new AddRoomViewModel();
vm.setRepository = StorageService.getRoomRepository();
return vm;
};
var createAddUnitVM = function () {
var vm = new AddUnitViewModel();
vm.setRepository = StorageService.getUnitRepository();
return vm;
};
var createPageVM = function () {
var vm = new PageViewModel();
return vm;
};
return {
createPageVM:createPageVM,
createAddRoomVM: createAddRoomVM,
createAddUnitVM: createAddUnitVM
};
});
And the module calling the factory
define("ApplicationViewModel", ["ViewModelFactory"],
function (viewModelFactory) {
mainVM = null;
var initVM = function () {
mainVM = {
page: viewModelFactory.createPageVM(),
addRoom: viewModelFactory.createAddRoomVM(),
addUnit: viewModelFactory.createAddUnitVM()
};
};
var getVM = function (viewName) {
switch (viewName) {
case "AddRoom":
return mainVM.addRoom;
case "AddUnit":
return mainVM.addUnit;
default:
return null;
}
};
var getPageVM = function () {
return mainVM.page;
};
return {
initVM: initVM,
getVM: getVM,
getPageVM: getPageVM,
mainVM: mainVM
};
});
And the class containing the applicationViewModel:
define("Bootstrapper", ["knockout-2.1.0", "Routing", "ApplicationViewModel"],
function (ko, routing, applicationViewModel) {
var run = function () {
applicationViewModel.initVM(); <-- after here mainVM.page is null
var mainVM = applicationViewModel.mainVM;
routing.initRouting(applicationViewModel);
ko.applyBindings(mainVM);
routing.showView("StartPage");
alert("Start");
};
return {
run: run
};
})
Your problem may have been caused by Knockout 2.1, which didn't work well when ko was not a global variable.
Knockout 2.2 should work fine, and I see from your comment this did indeed fix the problem.