[英]How to fix 'Uncaught TypeError: tagsInput is not a constructor' error while initiating custom JavaScript plugin two times on the same page
I've created a tags input Vanilla JS plugin. 我创建了一个标签输入Vanilla JS插件。 It's working fine when I initiate it for the first time.
当我第一次启动它时,它工作正常。 but when I re-initiate for another input tag.
但是当我重新启动另一个输入标签时。 It throws this error:
Uncaught TypeError: tagsInput is not a constructor
. 它将引发以下错误:
Uncaught TypeError: tagsInput is not a constructor
。
Working plugin code on Codepen Codepen上的有效插件代码
I've removed the extra code from the plugin for now. 我现在已经从插件中删除了多余的代码。
Plugin: 插入:
(function () {
var tagsInput = function (opts) {
this.arr = [];
this.input = document.createElement("input");
this.wrapper = document.createElement("div");
this.options = Object.assign(tagsInput.defaults, opts);
this.originalInput = document.getElementById(opts.selector);
buildUI(this);
addEvents(this);
}
function buildUI(tags) {
//build UI code here
}
function addEvents(tags) {
// add events to tags here
}
tagsInput.prototype.addTag = function (str) {
// add tags code
}
tagsInput.prototype.deleteTag = function (tag, i) {
// delete tags code
}
tagsInput.prototype.anyError = function (str) {
// find errors
}
tagsInput.prototype.addData = function (data) {
// add prefill data
}
tagsInput.defaults = {
selector: '',
duplicate: false,
max: null,
wrapperClass: 'tags-input-wrapper',
tagsClass: 'tag'
}
//make it global
window.tagsInput = tagsInput;
})();
When I initialize it two times on the same page it throws an error. 当我在同一页面上对其进行两次初始化时,将引发错误。
Initializing the plugin: 初始化插件:
var tagsInput = new tagsInput({
selector: 'demoInput',
duplicate: false,
max: 4,
wrapperClass: 'tags-input-wrapper',
tagsClass: 'tag'
});
tagsInput.addData(["aloo", "bhindi", "tamater"]);
You are assigning tagsInput
to a instance of tagsInput
. 您分配
tagsInput
到的实例tagsInput
。 Now when you reference it, It will be an instance of tagsInput
not the constructor. 现在,当您引用它时,它将是
tagsInput
的实例, tagsInput
不是构造函数。 You can fix it by changing var tagsInput = new tagsInput({
to something like this: var tagsInputOne = new tagsInput({
or var demoInput = new tagsInput({
. 您可以通过将
var tagsInput = new tagsInput({
更改为以下内容来修复此问题: var tagsInputOne = new tagsInput({
或var demoInput = new tagsInput({
。
Hopefully, this helps. 希望这会有所帮助。
You're reassigning tagsInput
to an element constructed by tagsInput
- as such this will work exactly once, then because there is no longer any reference to the old tagsInput
constructor, it will be garbage collected. 您正在将
tagsInput
重新分配给tagsInput
构造的tagsInput
-这样将只工作一次,然后,因为不再有对旧tagsInput
构造函数的引用,将对其进行垃圾回收。 Either change the name of the variable: 更改变量名称:
var demoInput = new tagsInput({...});
Or change tagsInput
to be capitalized as is constructor naming convention: 或将
tagsInput
更改为大写,如构造函数命名约定所示:
var TagsInput = function(opts) {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.