Custom Windows 8 controls with HTML + JS
One of my pet peeves about developing on the .NET platform prior to Silverlight 5 was the difficulty in binding to data where the schema is not known at compile time. Since then, we have ICustomTypeProvider which can direct the data binding machinery to bind to dictionaries or any custom data structure.
Unfortunately, ICustomTypeProvider is not available on WinRT. I asked Nick Hodges @nickhodgeMSFT at #WinDevAu today what were the options, and he suggested I have a look at HTML + js instead.
When asked whether MS was going to be restrictive about running downloaded code on a device, as Apple is, he suggested I try it.
For what it’s worth, the following code works in Consumer Preview.
eval("var myfunc = function() { return 'ab' + 'cd'; };
var result = myfunc();
document.getElementById("testLabel").innerText = result;
This led me to have a look at the JS samples more closely. The first thing that caught my attention was the following
<div id="output" data-win-control="SdkSample.ScenarioOutput">
<div id="box1" class="box">&nbsp;</div>
<div id="box2" class="box">&nbsp;</div>
</div>
What is this SdkSample.ScenarioOutput?
I dug a little further and this is what I found:
var ScenarioOutput = WinJS.Class.define(
function (element, options) {
element.winControl = this;
this.element = element;
new WinJS.Utilities.QueryCollection(element)
.setAttribute("role", "region")
.setAttribute("aria-labelledby", "outputLabel")
.setAttribute("aria-live", "assertive");
element.id = "output";
this._addOutputLabel(element);
this._addStatusOutput(element);
}, {
_addOutputLabel: function (element) {
var label = document.createElement("h2");
label.id = "outputLabel";
label.textContent = "Output";
element.parentNode.insertBefore(label, element);
},
_addStatusOutput: function (element) {
var statusDiv = document.createElement("div");
statusDiv.id = "statusMessage";
element.insertBefore(statusDiv, element.childNodes[0]);
}
}
);
You can construct a WinJS class in javascript! There are three parameters:
- constructor – a function
- instanceMembers – object – set of instance fields and methods on the class
- staticMembers – object -set of static fields and methods
So in our example above, the function takes an element and the constructor creates new attributes
and adds any custom behaviors. The instance methods are used as a prototype for the constructed
instances.
Which leaves one last open question, how do static methods work in Javascript any way?
1 Comment
Jump to comment form | comments rss [?]