Created
January 16, 2016 11:42
-
-
Save paranoidjk/ed1ee1e04ec0525abd5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;(function(win, ctrl) { | |
| var incId = 0; | |
| function ControlName(element, options) { | |
| var that = this; | |
| var id = Date.now() + '-' + (++incId); // 每个控件有唯一的id | |
| var root = document.createDocumentFragment(); // 文档片段,用于append时提高效率 | |
| if (arguments.length === 1 && !(arguments[0] instanceof HTMLElement)) { | |
| // 参数个数的兼容判断 | |
| options = arguments[0]; | |
| element = null; | |
| } | |
| if (!element) { | |
| // 如果不是从已有DOM元素创建控件,则可以新建一个元素 | |
| element = document.createElement('div'); | |
| } | |
| root.appendChild(element); | |
| options = options || {}; | |
| element.setAttribute('data-ctrl-name', 'controlname'); | |
| element.setAttribute('data-ctrl-id', id); | |
| // 编写控件的属性 | |
| var theProperty; | |
| Object.defineProperty(this, 'theProperty', { | |
| get: function() { | |
| return theProperty; | |
| }, | |
| set: function(v) { | |
| if (v) { // 可以对v进行一些校验 | |
| thePropery = v; | |
| } else { | |
| throw new Error('Non expected value'); | |
| } | |
| } | |
| }); | |
| this.theProperty = options.theProperty || 'defaultValue'; // options中的初始化参数 | |
| // vm属性的获取和设置 | |
| var viewModel; | |
| Object.defineProperty(this, 'viewModel', { | |
| get: function() { | |
| return viewModel; | |
| }, | |
| set: function(v) { | |
| if (v) { | |
| viewModel = v; | |
| that.syncViewModel(); // 自动同步数据和视图 | |
| } else { | |
| throw new Error('Non expected value'); | |
| } | |
| } | |
| }); | |
| // 同步数据和视图的方法 | |
| this.syncViewModel = function() { | |
| // 数据的同步和更新操作 | |
| } | |
| // 事件代理 | |
| this.addEventListener = function() { | |
| element.addEventListener.apply(element, arguments); | |
| } | |
| this.removeEventListener = function() { | |
| element.removeEventListener.apply(element, arguments); | |
| } | |
| // 移除控件元素 | |
| this.remove = function() { | |
| if (element.parentNode) { | |
| element.parentNode.removeChild(element); | |
| } | |
| } | |
| this.element = element; | |
| this.root = root; | |
| } | |
| ctrl.controlname = ControlName; | |
| })(window, window['ctrl'] || (window['ctrl'] = {})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment