jQuery has the function append
that can be used like this:
$(whatever).append('abc') // Append string
$(whatever).append(document.createElement('div')) // Append an element
$(whatever).append($('<div></div>')) // Passing a jQuery object
The last one means that the jQuery object must have some function (as JS has no types and it's just an object) which returns the append function the html in some way, or something similar.
In order to make my code as nice as possible, I wanted to make something like:
class Component {
name;
constructor(name) {
this.name = name;
}
FUNCTIONREFERED() {
return $(document.createElement('input'))
.attr('name', this.name);
}
}
$('body').append(new Component('example'));
I have looked at the documentation and found nothing, I also took a look at the properties and functions of the object that is returned and saw nothing special.
I tried a few, imagine it was the html
function (to say an example), then I could return the closure so jQuery could paint it:
class Component {
name;
constructor(name) {
this.name = name;
}
html() {
return $(document.createElement('input'))
.attr('name', this.name)
.html;
}
}
$('body').append(new Component('example'));
I don't want to pass a string like this:
$('body').append(new Component('example').html());
I want the object itself to be appendable like the jQuery object is.
CodePudding user response:
class Component {
name;
constructor(name) {
this.name = name;
}
html() {
return $(document.createElement('input'))
.attr('name', this.name);
}
}
$('body').append(new Component('example').html());
CodePudding user response:
As some comments suggested, it is possible to return another object in the constructor of a class in JS.
So it could be something like:
class Component {
constructor() {
return $('<div></div>');
}
}
$('body').append(new Component());
It does not behave like a jQuery object, it becomes one. It's acceptable!
Thanks!