Monday, June 15, 2009

Google Maps API v3, MVCObject


這算是 v3 的一個特點,使用了 MVC 架構來組織程式。其 MVC 架構的核心就是 MVCObject,不過基本上就是有系統的使用之前提到的 event system,用以通知該收到某一事件的物件。
function MVCObject() {
  this.bindValues = {};
  this.bindListeners = {}
 }
有兩個屬性,一個記錄自已正在接收哪些物件的哪些 event,另一個是接收 event 用的 listener。

最重要的就是 bindTo:
J = MVCObject["prototype"];
 // Binds a View to a Model.
 // key:string, target:MVCObject, targetKey:string, noNotify?:boolean
 // after bind, the set value or get value will call the model object. 
 J.bindTo = function(key, target, targetKey, noNotify) {
  var e = this;
  e["unbind"](key);
  (e.bindListeners[key] = {
   target : target,
   kk : targetKey
  }).Ud = event["addListener"](target, targetKey + "_changed", function() {
     e.notify(key)
    });
  this.bindValue(key, target, targetKey, noNotify)
 };
 J.bindValue = function(key, target, targetKey, noNotify) {
  this.bindValues[key] = {
   object : target,
   targetKey : targetKey
  };
  noNotify || this.notify(key)
 };

 // Notify observers of a change.
 // key:string
 J.notify = function(key) {
  var b = key + "_changed";
  this[b] ? this[b]() : this.changed(key);
  event["trigger"](this, b)
 };
表示要用本身的 key 事件來接收 target 的 targetKey 的事件,這代表,當 target 的 targetKey_changed 被觸發時,即會呼叫本身的 notify。 而呼叫 notify 通常代表的就是 key_changed functoin 被呼叫,和 key_changed event 被觸發。而除了接收 event 的觸發方式外,就是直接去設值的觸發方式了:
// Sets a value.
 // key:string, value:*
 J.set = function(key, value) {
  if (this.bindValues.hasOwnProperty(key)) {
   var c = this.bindValues[key], d = c.targetKey, e = c.object, g = "set_" + d;
   e[g] ? e[g](value) : e.set(d, value)
  } else {
   this[key] = value;
   this.notify(key)
  }
 };
set 會呼叫 set_key 的 function ,如果沒有定義的話,就會去 notify key event,而進而就會觸發在接收此 event 的物件。

有 bindTo 就會有 unbind,就是解除先前定義的 bind 關係。
// Removes a bind.
 // key:string
 J.unbind = function(key) {
  var b = this.bindListeners[key];
  if (b) {
   delete this.bindListeners[key];
   event["removeListener"](b.Ud);
   this.unbindValue(key)
  }
 };

 J.unbindValue = function(key) {
  var b = this.get(key);
  delete this.bindValues[key];
  this[key] = b
 };

雖然 MVCObject 的程式不大,但卻是 v3 非常重要的物件,大部分 v3 的物件都是繼承自 MVCObject ,而進而獲得可 bind 其他物件,收發 event 的能力。

0 comments:

Post a Comment