Creating Composite Javascript / HTML Widgets

What I would like to do is dynamically create a standalone HTML block with additional properties.

I'm not sure what to call it, because now a “widget” means that it is something like a miracle or icon to put on your blog. I'm talking about a reusable, customizable, “composite” JS / HTML object (/ CSS).

For example, a simple date picker.

document.body.appendChild(new DatePicker());

Generates

<div class="datepicker" name="...">
    <select class="datepicker_monthSelect">
        <option value="0">January</option>
        ....
    </select>
    <select class="datepicker_daySelect">
        <option value="1">1</option>
        ....
    </select>
    <select class="datepicker_yearSelect">
        <option value="2010">2010</option>
        ....
    </select>
</div>

And will have type properties

var d = new DatePicker();
d.value = "2010-06-21";
d.name = "the_datepicker";
d.month = 5;
d.month = "June";
d.day = 21;
d.year = 2010;

How can this be done (easily)? What are the best methods for this situation?

+3
source share
3 answers

MooTools . JavaScript toElement, DOM MooTools. toElement , , toElement() DOM. DOM appendChild.

function DatePicker(date) {
    this.date = date;
}

DatePicker.prototype.toElement = function() {
    // return a DOM representation of this object
};

var picker = new DatePicker();

:

// retrieve the DOM node directly
document.body.appendChild(picker.toElement());

// use a wrapper to append, that queries toElement first
// DOM is a function like jQuery, that wraps the given DOM
// object with additional methods like append for querying toElement.
DOM(document.body).append(picker);

, appendChild, .

, . , appendChild, , , toElement, , . , .

(function(original) {
    Element.prototype.appendChild = function(child) {
        if('toElement' in child) {
            original.call(this, child.toElement());
        }
        else {
            original.call(this, child);
        }
    }
})(Element.prototype.appendChild);

DOM, :

document.body.appendChild(new DatePicker());
+1

.

"" -, , Javascript , Object-Oriented. ( , yuck.)

, , , to_html DatePicker '.

DatePicker HTML.

HTML-, DatePicker, .

+1

Source: https://habr.com/ru/post/1751118/


All Articles