How can i override the event variable in jquery - javascript

On click of document anywhere by default, it is coming as false
I want to change it to true how can I do that..?
jQuery(document).click(function(e) {
console.log(e); //e.target.isConnected = false;
e.target.isConnected = true; //i want to overwrite
--logic--
--logic--
});
I am getting this error:
Uncaught TypeError: Cannot assign to read only property 'isConnected'
of object '[object HTMLAnchorElement]'
My application is in angular 4

The isConnected is property holding a status information and because of that it is read only, and cannot be changed using an assignment.
Node.isConnected
The isConnected read-only property of the Node interface returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM.

Related

Accessing & Manipulating DOM for JS Module

I'm new to importing modules in ES6. I have a simple module with a function for creating and appending an HTML element.
I am able to call and pass arguments to the function, however, I cannot read any properties from the DOM. I am receiving errors such as this:
Uncaught TypeError: Cannot read properties of null (reading 'parentNode')
I have simplified my code below:
main.js
import * as watm_fn from "./modules/functions.js";
document.addEventListener("DOMContentLoaded", function (event) {
watm_fn.createToggle("#container");
}
functions.js
export function createToggle(elm) {
const toggleElementID = document.getElementById(elm);
const languageToggle = document.createElement("select");
toggleElementID.parentNode.replaceChild(languageToggle, toggleElementID);
}
I get a similar error when trying to return the innerHTML of toggleElementID
Is accessing and manipulating the DOM via an imported module possible? And if so, what am I doing wrong?
(I am not using node or jquery in this project)
Well I feel dumb. I'm used to coding in jQuery where you include the "#" in front of your IDs, but I forgot that getElementById does not require that. Removing that from my passed argument resolved the issue.
Uncaught TypeError: Cannot read properties of null (reading 'parentNode')
This error suggests that the below line is failing toggleElementID is null:
toggleElementID.parentNode.replaceChild(languageToggle, elm);
Why is toggleElementID null ?
Look at the code searching for the element
const toggleElementID = document.getElementById(elm);
As per getElementById
An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.
So there is no matching element found with the supplied elm id.

Jest test fails when using window object environment variable?

My tests were running fine first, I am now using environmental variables based on the window object like:
{window._env_.REACT_APP_URL}
But when I run my test: it shows as TypeError: Cannot read property 'REACT_APP_URL' of undefined
Do I need to do something different in my test files to accept this type of variable, when I change to {process.env.REACT_APP_URL} everything works as expected?
Any idea's?
The _env_ property does not exist on the window object out of the box, hence TypeScript is complaining that you are assigning a value to an undefined property.
Best way to solve your issue is to reassign the window variable to a custom one that combines the current window types with your own custom EnvironmentVariables interface and use that in your tests instead:
interface EnvironmentVariables {
'_env_': {
'REACT_APP_URL': string
}
}
const customWindow = window as Window & typeof globalThis & EnvironmentVariables;
// set the _env_ object with values
customWindow._env_ = {
'REACT_APP_URL': 'url here'
}
// access REACT_APP_URL
customWindow._env_.REACT_APP_URL

Trying to test whether element has attribute without directly assessing the element

Trying to create query object on clicks on various buttons by sending attributes on html called "attr-{{foo}}" which get their name from an ng-repeat or some other means. I wanted on controller that first tests if the element has all attributes that map onto the keys of the query object in the scope, and continue this if else chain down to having only one attribute; however, when I tried this, I would get the error "cannot find .value of 'null'", as I was testing with
(below you will find a snippet that is representative of my controller)
vm.openFoos = function (event) {
if (event.target.attributes.getNamedItem('attr-foo').value &&
!event.target.attributes.getNamedItem('attr-bar').value) {
var obj = {
foo: event.currentTarget.attributes.getNamedItem('attr-foo').value,
name: $routeParams.name
} else if {
(event.target.attributes.getNamedItem('attr-foo').value &&
event.target.attributes.getNamedItem('attr-bar').value) {
var obj = {
foo: event.currentTarget.attributes.getNamedItem('attr-foo').value,
name: $routeParams.name,
bar: event.currentTarget.attributes.getNamedItem('attr-bar').value
}
}
data.getReviews(obj)
.success(function (data){$log.debug(data)}).error(function(e){$log.debug(e)});
};
This works if I click on elements with both attr-foo and attr-bar (as by the convention of this testing from most strict case of having attributes to least, I know if I had written the if statements in reverse I would get the error "cannot find value of null". Sample HTML:
<span class="one" ng-click="vm.openFoos($event) attr-foo="foooo">Click FOOO</span>
<span class="two" ng-click="vm.openFoos($event) attr-foo="fo" attr-bar="bar">Click FOO BAR</span>
Clicking span.one throws the error "cannot find value of null" but clicking span.two works fine.
I do not want to write a controller for each instance of the combinations of keys in my query appearing on various html attributes; however, I'm getting this error.
instead of using
if (event.currentTarget.attributes.getNamedItem('attr-thing').value ....
use
if (event.currentTarget.attributes.getNamedItem('attr-thing') ....
When
event.currentTarget.attributes.getNamedItem('attr-thing')
does not exist, obviously one cannot take the value of it!
Could you be looking for hasOwnProperty?
object.hasOwnProperty("attrname"); // Yields true or false.

cannot read property 'push' of null

I have a page which works on my localhost.. when I put t on a remote server, it gave an error. the code which returns the error is
var $app_list = localStorage.getItem('LsAppList');
var AppListJson = JSON.parse($app_list);
AppListJson.push({
"extapp_id": appdetail.get("addAppId"),
"desc": appdetail.get("addAppName"),
"device_no": appdetail.get("devicenoValue"),
"validation_key": appdetail.get("activationkeyValue")
});
the console log is
Uncaught TypeError: Cannot read property 'push' of null
addToJson EncigoHome.js:126
n.extend.trigger kendo.mobile.min.js:9
s.extend._release kendo.mobile.min.js:15
i._userEvents.o.UserEvents.tap kendo.mobile.min.js:15
n.extend.trigger kendo.mobile.min.js:9
l.extend.notify kendo.mobile.min.js:13
u.extend._trigger kendo.mobile.min.js:13
u.extend.end kendo.mobile.min.js:13
l.extend._eachTouch kendo.mobile.min.js:13
l.extend._end kendo.mobile.min.js:13
arguments.length.t.(anonymous function) kendo.mobile.min.js:10
b.event.dispatch jquery-1.9.1.js:9593
v.handle
localStorage is per domain (more specifically same origin). The localStorage associated with the remote domain does not have access to the values stored in the localStorage associated with your localhost.
You should check to see if there is a stored value and fallback to a default one or treat the error:
var $app_list = localStorage.getItem('LsAppList');
var AppListJson = $app_list != null ? JSON.parse($app_list) : [];
//...
More verbose:
var $app_list = localStorage.getItem('LsAppList'),
AppListJson;
if ($app_list != null) {
AppListJson = JSON.parse($app_list);
} else {
// treat no LsAppList stored case
// you could show a message or set it to a default value
AppListJson = [];
}
This "no previously stored data" scenario will happen whenever the user clears his browser data or switches browsers/devices as well, so it must be treated properly.
The root cause of the error, as you've probably figured out already, is that localStorage.getItem(key) returns null when no value is stored for the given key in the current domain. Then JSON.parse(null) === null and null.push() throws.
Just as a nitpick, I'd suggest reviewing your variables naming:
Don't use PascalCase naming for non-constructors.
Don't mix camelCase with underline naming conventions.
Recommended read: Idiomatic.js naming.
And also, AppListJson is not JSON, it is a native array. JSON can only exist in string context, that is, your $app_list is JSON. More in-depth explanation about JSON/not JSON: There's no such thing as a "JSON Object"
The .push() method can only be used on arrays.
It seems that you don't have the item stored in localStorage, which is why it is returning null

ExtJS 4 Object.prototype fail

have a bit problem to use prototype while using framework ExtJS version 4.1.1.
At first I made my prototypings before I load ExtJS.
On "Array.prototype.xyz" and "String.prototype.xyz" all work fine.
Bot on "Object.prototype.xyz" there is a bad behavior in mixin inclusion of ExtJS.
Example my test code:
Object.prototype.doSomething = function() {
console.log('I do it!');
}
var a = {};
a.doSomething();
Error message from ExtJS:
Uncaught TypeError: Cannot read property '$childEls' of undefined
And break.
And:
- Yes. Without "Uncaught TypeError: Cannot read property '$childEls' of undefined" it work
fine.
- No. I use not oter mixins currently.
- Yes. I try to use only one dummy panel Component.
Question: Is there a simple solution to prototype on Object class-object?
The problem stems from one of the fundamental methods of the Ext JS library: Ext.merge
Proving this is very simple:
Object.prototype.doSomething = function(){ console.log("Does something"); };
var emptyObj = {};
console.log(emptyObj.hasOwnProperty("doSomething")); // Prints "false"
var mergeObj = Ext.merge({}, {a: "b"});
console.log(mergeObj.hasOwnProperty("doSomething")); // Prints "true"
Basically, every time Ext.merge (or Ext.apply) is called with an object literal your prototype method is "promoted" up the prototype chain. When you go to create a panel (or any component, really) the class mixin object is merged with its prototype's mixin object. Since a mixin is defined as an object literal in the class definition, your "doSomething" method is promoted.
Then in Ext.util.ElementContainer#getClassChildEls, the mixin object is iterated over assuming each property is an existing class and tries to access mixins[name].self.$childEls (where mixins[name] is your "doSomething" method). Your method doesn't have a self property so accessing $childEls throws the error.
If you need an object available on every object, write it as a static method like Object.doSomething or even Ext.Object.doSomething.

Categories