Idea
We're trying to build simple MVVM version that similar to HtmlJs.
MVVM must work with data bound to an input and a text. Both of them must be synchronized. Firstly, we need to update text when input's value control changed.
Firstly, we need to define a wrapper for data (aka observer);
var observedData = function (data) { var _data = data, // save init data targets = []; // all functions for manipulating HTML Element // the function used for get/set data var init = function (newVal) { if (!newVal) { // if nothing passed, we want to get lastest value return _data; } // if there we pass parameter, it mean setting new value for observer _data = newVal; // refresh all targets, aka all DOM manipulating function for (var i = 0, j = targets.length; i < j; i++) { targets[i].call(targets[i], _data); } }; // subscribe a function // save that function to an array init.subscribe = function (callback) { targets.push(callback); }; // return a function for making a new closure return init; };Then we define controls. Only input and text are defined, however, the number of control is not important. We can usually define more after all.
(function () { var element; // this is the current Element var html = function (ele) { element = ele; // always return html for fluent API return html; }; html.change = function (callback) { element.addEventListener('change', callback, false); return html; }; html.input = function (observer) { var inp = document.createElement('input'); inp.value = observer(); element.appendChild(inp); element = inp; // set the reference html.change(function (e) { var value = (e.srcElement || e.target).value; observer(value); // notify change here }); return html; }; html.span = function (observer) { var span = document.createElement('span'); span.innerHTML = observer(); element.appendChild(span); element = span; // whenever input' value changed, change the text of the span observer.subscribe(function (val) { span.innerHTML = val; }); return html; }; // go to parent context html.$ = function () { element = element.parentElement; return html; }; // export symbol window.html = html; })();Then user uses controls as following.
var helloWorld = observedData('Hello world!'); html(document.body) .input(helloWorld).$() .span(helloWorld).$()
1. export - define
-method - no returnDefine a module by a key. The reason a add define function is that export is reserved keyword. If you want to use "export", please access it by string html['export']
Param | Type | Details |
---|---|---|
key | String | Key of your module. |
obj | Object | Object for export. |
html.define('$', jQuery);
2. import
-method - return ObjectGet a module by its key.
Param | Type | Details |
---|---|---|
key | String | Key of your module. |
var $ = html.import('$');