Idea
MVVM must work with bind data 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, targets = []; var getterSetter = function (newVal) { if (!newVal) { // if nothing passed, user wants to get return _data; } _data = newVal; for (var i = 0, j = targets.length; i < j; i++) { targets[i].call(targets[i], _data); } }; getterSetter.subscribe = function (callback) { targets.push(callback); }; // return a function for making a new closure return getterSetter; };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 html = {}, element; html.setContainer = 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); 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); // 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.setContainer(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('$');