angular雙向綁定簡單實現

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語法實現雙向綁定

  • 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屬性啓用與元素值的雙重綁定。
複製代碼

實現步驟

  1. 解析模板並實例化控制器(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);
複製代碼
  1. 查找具備使用控制器屬性的綁定的元素
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);
    });
複製代碼
  1. 使用代理檢測代碼中的更新
// 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);
    }
});
複製代碼
  1. 對元素事件作出反應:
  • 最後要作的是對用戶交互作出反應。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!';   
}
複製代碼

參考連接

相關文章
相關標籤/搜索