angular雙向繫結簡單實現
雙向繫結原理
- 宣告一個新元件時,將使用代理設計模式來代理每個屬性(getter和setter)。因此,它將能夠從程式碼和使用者輸入中檢測屬性值變化
代理proxy:
- Proxy 可以理解成,在目標物件之前架設一層“攔截”,外界對該物件的訪問,都必須先通過這層攔截,因此提供了一種機制,可以對外界的訪問進行過濾和改寫。
- 示例
var account = {
balance: 5000
}
// get方法攔截
var bank = new Proxy(account, {
get: function (target, prop) {
return 9000000;
}
});
console.log(account.balance); // 5,000 (your real balance)
console.log(bank.balance); // 9,000,000 (the bank is lying)
console.log(bank.currency); // 9,000,000 (the bank is doing anything)
// set方法攔截
var bank = new Proxy(account, {
set: function (target, prop, value) {
// Always set property value to 0
return Reflect.set(target, prop, 0);
}
});
account.balance = 5800;
console.log(account.balance); // 5,800
bank.balance = 5400;
console.log(account.balance); // 0 (the bank is doing anything)
複製程式碼
模仿angular語法實現雙向繫結
<div ng-controller="InputController">
<!-- "Hello World!" -->
<input ng-bind="message"/>
<input ng-bind="message"/>
</div>
<script type="javascript">
function InputController () {
this.message = `Hello World!`;
}
angular.controller(`InputController`, InputController);
</script>
複製程式碼
根據angular的語法,首先定義具有屬性的controller。然後在模板中使用此控制器。最後,使用ng-bind屬性啟用與元素值的雙重繫結。
複製程式碼
實現步驟
- 解析模板並例項化控制器(controller)
- 要使屬性繫結,我們需要獲得一個位置(也稱為控制器)來宣告這些屬性。因此,有必要定義一個控制器並將其引入我們的框架。
- 在控制器宣告期間,框架將查詢具有ng-controller屬性的元素。
- 如果它匹配其中一個宣告的控制器,它將建立該控制器的新例項。此控制器例項僅負責此特定模板。
var controllers = {};
var addController = function (name, constructor) {
// Store controller constructor
controllers[name] = {
factory: constructor,
instances: []
};
// Look for elements using the controller
var element = document.querySelector(`[ng-controller=` + name + `]`);
if (!element){
return; // No element uses this controller
}
// Create a new instance and save it
var ctrl = new controllers[name].factory;
controllers[name].instances.push(ctrl);
// Look for bindings.....
};
addController(`InputController`, InputController);
複製程式碼
- 查詢具有使用控制器屬性的繫結的元素
var bindings = {};
// Note: element is the dom element using the controller
Array.prototype.slice.call(element.querySelectorAll(`[ng-bind]`))
.map(function (element) {
var boundValue = element.getAttribute(`ng-bind`);
if(!bindings[boundValue]) {
bindings[boundValue] = {
boundValue: boundValue,
elements: []
}
}
bindings[boundValue].elements.push(element);
});
複製程式碼
- 使用代理檢測程式碼中的更新
// Note: ctrl is the controller instance
var proxy = new Proxy(ctrl, {
set: function (target, prop, value) {
var bind = bindings[prop];
if(bind) {
// Update each DOM element bound to the property
bind.elements.forEach(function (element) {
element.value = value;
element.setAttribute(`value`, value);
});
}
return Reflect.set(target, prop, value);
}
});
複製程式碼
- 對元素事件做出反應:
- 最後要做的是對使用者互動做出反應。DOM元素在檢測到值更改時觸發事件。偵聽這些事件並使用事件中的新值更新繫結屬性。繫結到同一屬性的所有其他元素將由於代理而自動更新。
Object.keys(bindings).forEach(function (boundValue) {
var bind = bindings[boundValue];
// Listen elements event and update proxy property
bind.elements.forEach(function (element) {
element.addEventListener(`input`, function (event) {
proxy[bind.boundValue] = event.target.value; // Also triggers the proxy setter
});
})
});
複製程式碼
全部程式碼整合
/* html code */
<div ng-controller="InputController">
<input ng-bind="message"/>
<input ng-bind="message"/>
<button onclick="onButtonClick()">Click!</button>
</div>
/* Framework code */
(function () {
var controllers = {};
var addController = function (name, constructor) {
// Store controller constructor
controllers[name] = {
factory: constructor,
instances: []
};
// Look for elements using the controller
var element = document.querySelector(`[ng-controller=` + name + `]`);
if (!element){
return;
}
// Create a new instance and save it
var ctrl = new controllers[name].factory();
controllers[name].instances.push(ctrl);
// Get elements bound to properties
var bindings = {};
Array.prototype.slice.call(element.querySelectorAll(`[ng-bind]`))
.map(function (element) {
var boundValue = element.getAttribute(`ng-bind`);
if (!bindings[boundValue]) {
bindings[boundValue] = {
boundValue: boundValue,
elements: []
}
}
bindings[boundValue].elements.push(element);
});
// Update DOM element bound when controller property is set
var proxy = new Proxy (ctrl, {
set: function (target, prop, value) {
var bind = bindings[prop];
if (bind) {
bind.elements.forEach(function (element) {
element.value = value;
element.setAttribute(`value`, value);
});
}
return Reflect.set(target, prop, value);
}
});
// Listen DOM element update to set the controller property
Object.keys(bindings).forEach(function (boundValue) {
var bind = bindings[boundValue];
bind.elements.forEach(function (element) {
element.addEventListener(`input`, function (event) {
proxy[bind.boundValue] = event.target.value;
});
})
});
// Fill proxy with ctrl properties
// and return proxy, not the ctrl !
Object.assign(proxy, ctrl);
return proxy;
}
// Export framework in window
this.angular = {
controller: addController
}
})();
/* User code */
function InputController () {
this.message = `Hello World!`;
}
var myInputController = angular.controller(`InputController`, InputController);
function onButtonClick () {
myInputController.message = `Clicked!`;
}
複製程式碼
參考連結