Best approach to handle “Cannot read property 'addEventListener' of null” errors

笑着哭i 提交于 2019-12-25 00:38:24

问题


Currently what i do is checking if element exist in page. But my code has alot if conditions because of that. Jquery event listeners doesnt show errow when element doesnt exist. How jquery handles that and what texniques can i use for better design ?

var el = document.getElementById('el');
var another_el = document.getElementById('another_el');

if(another_el){
el.addEventListener('click', swapper, false);
}

if(el){
  el.addEventListener('click', swapper, false);
}
....
...

回答1:


How jquery handles that...?

jQuery's API is set-based, not element-based. The DOM's API is element-based. When you do $("#foo").on("click", ...) in jQuery, if there's no element with the id "foo", $() returns an empty set, not null, and calling on on that set doesn't do anything, but doesn't cause an error either.

Since getElementById returns an element or null, you have to have the check you've shown to prevent trying to call methods on null, which causes an error.

If you want the benefits of a set-based API without using jQuery, you could write your own set of utility functions that use querySelectorAll to give yourself a thin set-based wrapper around the DOM API, if you like.

Here's a very simple starter example:

// The object we use as the prototype of objects returned by `domSet`
var domSetMethods = {
    on: function(eventName, handler) {
            // Loop through the elements in this set, adding the handler
            this.elements.forEach(function(element) {
                element.addEventListener(eventName, handler);
            });
            // To support chaining, return `this`
            return this;
        }
};
// Get a "DOM set" for the given selector
function domSet(selector) {
  // Create the set, usign `domSetMethods` as its prototype
  var set = Object.create(domSetMethods);
  // Add the elements
  set.elements = Array.prototype.slice.call(document.querySelectorAll(selector));
  // Return it
  return set;
}

domSet("#foo").on("click", function() {
  console.log("foo clicked");
});
// Notice that even though there's no id="bar" element, we don't get an error
domSet("#bar").on("click", function() {
  console.log("bar clicked");
});
<div id="foo">foo element (there is no bar element)</div>

You could add methods to domSetMethods that do other things. To support the chaining style of API jQuery provides, you return this in most cases from those methods.



来源:https://stackoverflow.com/questions/50602547/best-approach-to-handle-cannot-read-property-addeventlistener-of-null-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!