Add safety checks to dispatchEvent