JavaScript庫:observejs
observejs 用于觀察任意對象的任意變化的類庫,以輕巧、實用、強大而聞名。
ps:源代碼未壓縮版僅僅只有158行代碼:)
3分鐘精通 observe.js
對象字面量
var obj = { a: 1 }; observe(obj, function (name, value , old) { console.log(name + "__" + value + "__" + old); }); obj.a = 2; //a__2__1
數組
var arr = [1, 2, 3]; observe(arr, function (name, value, old) { console.log(name + "__" + value+"__"+old); }); arr.push(4);//Array-push__[1,2,3,4]__[1,2,3] arr[3] = 5;//3__5__4
復雜對象
var complexObj = { a: 1, b: 2, c: [{ d: [4] }] }; observe(complexObj, function (name, value , old, path) { console.log(name + "__" + value + "__" + old); //d__100__4 console.log(path) //#-c-0 }); complexObj.c[0].d = 100;
普通對象
var User = function (name, age) { this.name = name; this.age = age; //只監聽name observe(this,["name"] function (name, value, oldValue) { console.log(name + "__" + value + "__" + oldValue); }); } var user = new User("lisi", 25); user.name = "wangwu";//name__wangwu__lisi user.age= 20; //什么都輸出,因為沒有監聽age
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!