點擊查看基礎Proxy認知
這篇我們集中如何使用js實現類似vue的簡單數據雙向綁定;
拿input和textarea兩個html標簽作為展示
show.gif
two-way data binding
一、html
<input type="text" id="inputName" />
<textarea name="haha" id="myArea" cols="30" rows="10">hello world</textarea>
二、js代碼
Proxy: target -- handler -- traps
//創建一個對象
const myUser = {
id:'inputName',
name:'' //用來存儲和更新input的value值
};
//第一步:當用戶改變input輸入值時更新myUser.name ,通過onchange事件處理程序來實現
inputChange(myUser);
function inputChange(myObject) {
if (!myObject || !myObject.id) return; //如果傳入的對象不存在或者沒有id屬性,return出去
const input = document.getElementById(myObject.id); //通過對象里的id從而獲取對應id的input標簽
input.addEventListener('onchange', function(e) {
myObject.name = input.value;
});
}
//第二步:在js代碼中修改myUse.name時,跟新input里的內容,這一步略微復雜,但是proxy代理提供了一個解決方案
const inputHandler = {
set:function (target,prop,newValue) {
if(prop =='name' && target.id ) { //prop指的是傳入的對象里的屬性:
//更新對象的屬性
target[prop] = newValue;
document.getElementById(target.id).value = newValue;
return true; //set方法返回值只有false或true;
}
else return false;
}
};
//創建proxy
const myUserProxy = new Proxy(myUser,inputHandler);
一、測試:
//手動設置一個新的名字:
myUserProxy.name = 'Lily';
console.log(myUserProxy.name); //Lily
console.log(document.getElementById('inputName').value); //Lily
預覽:靜態.png
二、方案1:原生js實現數據綁定
- oninput事件可以監聽框的value變化
- 為了實現實時,先將數據綁定提取出來成單獨的函數,這樣每次oninput事件觸發就調用一次getChange,
var myArea = document.getElementById('myArea');
//初始textarea的值先給input框
var input = document.getElementById('inputName');
input.value = myArea.value;
function getChange() {
myUserProxy.name =myArea.value;
console.log(myUserProxy.name); //Lily
console.log(document.getElementById('inputName').value); //Lily
}
myArea.oninput = function () {
getChange()
}
三:方案2:jQuery實現數據綁定
- 記得先引入jquery庫
- 為了實現實時,使用setTimeout間歇調用觸發keydown事件
$("#myArea").keydown(function () {
myUserProxy.name = $("#myArea").val();
console.log(myUserProxy.name); //Lily
console.log(document.getElementById('inputName').value); //Lily
});
setTimeout(function () {
$("#myArea").trigger('keydown')
},100);