<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <script type="text/javascript"> var ObserverObj = { /*依赖对象*/ FirstName: "J", LastName: "Q", Id: 1 } var ObserverManager = { /*观察器*/ Observers:[], /*观察对象集*/ AddObserver: function(item){/*加入观察对象*/ this.Observers.push(item); }, Change: function(obj){ /*改变对象行为*/ for(var item in obj){ ObserverObj[item] = obj[item]; }//改变数据依赖对象数据 for(var i = 0,len = this.Observers.length; i < len; i++){ var item = this.Observers[i]; item.Display(); //对象改变后,改变观察对象的行为Display; 为统一的接口 } } } var Header = function(){ /*观察对象Header*/ this.Display = function(){ alert(ObserverObj.FirstName); } } var Content = function(){ /*观察对象Content*/ this.Display = function(){ alert(ObserverObj.LastName); } } var Foot = function(){ /*观察对象Foot*/ this.Display = function(){ alert(ObserverObj.Id); } } /*绑定观察器动作*/ ObserverManager.AddObserver(new Header()); ObserverManager.AddObserver(new Content()); ObserverManager.AddObserver(new Foot()); </script> <!--使用方法--> <a href="javascript://" onclick="ObserverManager.Change({FirstName:‘江‘});">改变FirstName</a> <a href="javascript://" onclick="ObserverManager.Change({LastName:‘琪‘});">改变LastName</a> <a href="javascript://" onclick="ObserverManager.Change({Id:2});">改变Id</a> </body> </html>
观察者实例
时间: 2024-11-09 01:54:54