- A better way to create a new jQuery Element is by passing the Element options as the second parameter
jQuery DOCS- Creating New Elements
As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn)
can be used as a property of the object passed to the second parameter
- Define the click inside the Element options - no need to attach unnecessary listeners to other elements like
"body" or document, etc.
- Would be nice to define the
this.$el right at init inside the constructor, that way, your append function would do exactly what it says.
- Makes more sense to call a function by what it does, and that's
something.append_to(somewhere), not append_content. Actually, you don't need that method at all if you already use jQuery.
class ArtObj {
constructor(string) {
this.text = string;
this.$ = $("<a>", {
id: "hello",
text: "hello",
href: "#",
click: (e) => {
e.preventDefault()
console.log(this.text)
}
});
}
}
const art1 = new ArtObj("string_zz");
art1.$.appendTo("#artifact_wrapper");
<div id="artifact_wrapper"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Since it makes no sense to create a class that generates a reusable component with a fixed ID, makes more sense to allow the user of your class to pass into the desired bits and pieces:
class ArtObj {
constructor(options) {
this.$ = $("<a>", options);
}
}
const art1 = new ArtObj({
id: "hello_1", // ID must be unique!
text: "hello",
href: "#",
click: (e) => {
e.preventDefault();
console.log("string_zz");
}
});
art1.$.appendTo("#artifact_wrapper");
<div id="artifact_wrapper"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
therefore, given the above, seems unnecessary to use a class at all:
$("<a>", {
id: "hello_1", // ID must be unique!
text: "hello",
href: "#",
click: (e) => {
e.preventDefault();
console.log("string_zz");
},
appendTo: "#artifact_wrapper"
});
<div id="artifact_wrapper"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>