本篇介紹directive的簡單實現,主要學習其實現的思路及代碼的設計,需要的朋友參考下吧
2018年首個計劃是學習vue源碼,查閱了一番資料之後,決定從第一個commit開始看起,這將是一場持久戰!這篇介紹directive的簡單實現,主要學習其實現的想法及程式碼的設計(directive和filter擴充起來非常方便,符合設計模式中的 開閉原則 )。
構思API
<p id="app" sd-on-click="toggle | .button"> <p sd-text="msg | capitalize"></p> <p sd-class-red="error" sd-text="content"></p> <button class="button">Toggle class</button> </p> var app = Seed.create({ id: 'app', scope: { msg: 'hello', content: 'world', error: true, toggle: function() { app.scope.error = !app.scope.error; } } });
實作功能夠簡單吧--將scope中的資料綁定到app中。
核心邏輯設計
#指令格式
以sd- text="msg | capitalize" 為例說明:
sd 為統一的前綴標識
text 為指令名稱
#capitalize 為篩選器名稱
其中| 後面為篩選器,可以新增多個。 sd-class-red
中的red為參數。
程式碼結構介紹
main.js 入口文件
// Seed构造函数 const Seed = function(opts) { }; // 对外暴露的API module.exports = { create: function(opts) { return new Seed(opts); } }; directives.js module.exports = { text: function(el, value) { el.textContent = value || ''; } }; filters.js module.exports = { capitalize: function(value) { value = value.toString(); return value.charAt(0).toUpperCase() + value.slice(1); } };
就這三個文件,其中directives和filters都是配置文件,很易於擴展。
實作的大致想法如下:
1.在Seed實例建立的時候會依序解析el容器中node節點的指令
2.將指令解析結果封裝為指令對象,結構為:
屬性 | 說明 | 類型 |
---|---|---|
attr | 原始屬性,如sd-text
|
String |
#key | #對應scope物件中的屬性名稱 | String |
filters | 過濾器名稱清單 | Array |
definition | 該指令的定義,如text對應的函數 | Function |
argument | 從attr中解析出來的參數(只支援一個參數) | String |
#update | #更新directive時呼叫typeof def === 'function' ? def : def.update
|
Function |
#bind | 如果directive中定義了bind方法,則在bindDirective 中會呼叫 |
Function |
el | 存储当前element元素 | Element |
3.想办法执行指令的update方法即可,该插件使用了 Object.defineProperty 来定义scope中的每个属性,在其setter中触发指令的update方法。
核心代码
const prefix = 'sd'; const Directives = require('./directives'); const Filters = require('./filters'); // 结果为[sd-text], [sd-class], [sd-on]的字符串 const selector = Object.keys(Directives).map((name) => `[${prefix}-${name}]`).join(','); const Seed = function(opts) { const self = this, root = this.el = document.getElementById(opts.id), // 筛选出el下所能支持的directive的nodes列表 els = this.el.querySelectorAll(selector), bindings = {}; this.scope = {}; // 解析节点 [].forEach.call(els, processNode); // 解析根节点 processNode(root); // 给scope赋值,触发setter方法,此时会调用与其相对应的directive的update方法 Object.keys(bindings).forEach((key) => { this.scope[key] = opts.scope[key]; }); function processNode(el) { cloneAttributes(el.attributes).forEach((attr) => { const directive = parseDirective(attr); if (directive) { bindDirective(self, el, bindings, directive); } }); } };
可以看到核心方法 processNode 主要做了两件事一个是 parseDirective ,另一个是 bindDirective 。
先来看看 parseDirective 方法:
function parseDirective(attr) { if (attr.name.indexOf(prefix) == -1) return; // 解析属性名称获取directive const noprefix = attr.name.slice(prefix.length + 1), argIndex = noprefix.indexOf('-'), dirname = argIndex === -1 ? noprefix : noprefix.slice(0, argIndex), arg = argIndex === -1 ? null : noprefix.slice(argIndex + 1), def = Directives[dirname] // 解析属性值获取filters const exp = attr.value, pipeIndex = exp.indexOf('|'), key = (pipeIndex === -1 ? exp : exp.slice(0, pipeIndex)).trim(), filters = pipeIndex === -1 ? null : exp.slice(pipeIndex + 1).split('|').map((filterName) => filterName.trim()); return def ? { attr: attr, key: key, filters: filters, argument: arg, definition: Directives[dirname], update: typeof def === 'function' ? def : def.update } : null; }
以 sd-on-click="toggle | .button" 为例来说明,其中attr对象的name为 sd-on-click ,value为 toggle | .button ,最终解析结果为:
{ "attr": attr, "key": "toggle", "filters": [".button"], "argument": "click", "definition": {"on": {}}, "update": function(){} }
紧接着调用 bindDirective 方法
/** * 数据绑定 * @param {Seed} seed Seed实例对象 * @param {Element} el 当前node节点 * @param {Object} bindings 数据绑定存储对象 * @param {Object} directive 指令解析结果 */ function bindDirective(seed, el, bindings, directive) { // 移除指令属性 el.removeAttribute(directive.attr.name); // 数据属性 const key = directive.key; let binding = bindings[key]; if (!binding) { bindings[key] = binding = { value: undefined, directives: [] // 与该数据相关的指令 }; } directive.el = el; binding.directives.push(directive); if (!seed.scope.hasOwnProperty(key)) { bindAccessors(seed, key, binding); } } /** * 重写scope西乡属性的getter和setter * @param {Seed} seed Seed实例 * @param {String} key 对象属性即opts.scope中的属性 * @param {Object} binding 数据绑定关系对象 */ function bindAccessors(seed, key, binding) { Object.defineProperty(seed.scope, key, { get: function() { return binding.value; }, set: function(value) { binding.value = value; // 触发directive binding.directives.forEach((directive) => { // 如果有过滤器则先执行过滤器 if (typeof value !== 'undefined' && directive.filters) { value = applyFilters(value, directive); } // 调用update方法 directive.update(directive.el, value, directive.argument, directive); }); } }); } /** * 调用filters依次处理value * @param {任意类型} value 数据值 * @param {Object} directive 解析出来的指令对象 */ function applyFilters(value, directive) { if (directive.definition.customFilter) { return directive.definition.customFilter(value, directive.filters); } else { directive.filters.forEach((name) => { if (Filters[name]) { value = Filters[name](value); } }); return value; } }
其中的bindings存放了数据和指令的关系,该对象中的key为opts.scope中的属性,value为Object,如下:
{ "msg": { "value": undefined, "directives": [] // 上面介绍的directive对象 } }
数据与directive建立好关系之后, bindAccessors 中为seed的scope对象的属性重新定义了getter和setter,其中setter会调用指令update方法,到此就已经完事具备了。
Seed构造函数在实例化的最后会迭代bindings中的key,然后从opts.scope找到对应的value, 赋值给了scope对象,此时setter中的update就触发执行了。
下面再看一下 sd-on 指令的定义:
{ on: { update: function(el, handler, event, directive) { if (!directive.handlers) { directive.handlers = {}; } const handlers = directive.handlers; if (handlers[event]) { el.removeEventListener(event, handlers[event]); } if (handler) { handler = handler.bind(el); el.addEventListener(event, handler); handlers[event] = handler; } }, customFilter: function(handler, selectors) { return function(e) { const match = selectors.every((selector) => e.target.matches(selector)); if (match) { handler.apply(this, arguments); } } } } }
发现它有customFilter,其实在 applyFilters 中就是针对该指令做的一个单独的判断,其中的selectors就是[".button"],最终返回一个匿名函数(事件监听函数),该匿名函数当做value传递给update方法,被其handler接收,update方法处理的是事件的绑定。这里其实实现的是事件的代理功能,customFilter中将handler包装一层作为事件的监听函数,同时还实现事件代理功能,设计的比较巧妙!
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
以上是在vue中如何實作directive功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版
中文版,非常好用

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能