What I would like to do is be able to dynamically a block of self-contained HTML that has additional properties.
I’m not sure what to call it, as “widget” now implies it is something like flair or a badge to put on your blog. I am talking about a reusable, customizable, “composite” JS/HTML(/CSS) object.
For example, a simple date picker.
document.body.appendChild(new DatePicker());
Would generate
<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 would have properties like
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 (easily) accomplished? What are the best practices for this situation?
I like the MooTools approach of doing this. Any JavaScript object can define a
toElementmethod and you can append this object to the DOM using MooTools’ wrappers. The wrappers will query thetoElementproperty on the object, and if it exists, then the return value of callingtoElement()will be appended to the DOM. For this to work, you would have to use the wrappers for appending to DOM instead of usingappendChilddirectly.Here are some ways to go about using this:
Of course, you can always overwrite the native
appendChildmethod, however, I would not recommend this.For the sake of completeness, this is how you would do it though. Use a closure to hold on to the original
appendChildmethod, and replace it with a new method that first checks iftoElementis defined, and retrieves the element representation of that object if it does. Otherwise, proceed with adding the passed-in object as it is.Add the object to DOM as in your example: