Skip to main content

[Flex] pureMVC 練習筆記啪兔

由於 pureMVC Standard and MultiCore 兩個版本寫法幾乎沒啥差別,開發的專案都統一使用彈性比較大的 MultiCore 版本來實作。跟 pureMVC 相處了一陣子後,漸漸地對它也沒有什麼特別的不爽...快,所以 Cairngorm and pureMVC 的選擇,也就由 pureMVC 勝出了(當然是有惡勢力的...冏)。

以下的範例還是使用 pureMVC Standard 來實作喔!這個範例應該能更容易理解 Mediator, Command and Proxy 合作的模式。


1. 由 DataProxy 開始寫
這次的 DataProxy 負責的是將 input textfield 中的文字儲存起來也提供清除的方法。 DataProxy 並不認識任何 Mediator。
package com.mvc.model
{
import mx.collections.ArrayCollection;
import org.puremvc.as3.patterns.proxy.Proxy;

public class DataProxy extends Proxy
{
public static const NAME:String = 'dataProxy';
public static const DATA_UPDATED:String ="data_updated";
public static const SAVE_DATA:String = 'save_data';
public static const CLEAR_DATA:String = 'clear_data';
public function DataProxy()
{
super(NAME, new ArrayCollection);
}
public function save(obj:Object):void{
list.addItem(list.length+" : "+obj);
sendNotification( DATA_UPDATED, data );
}
public function clear():void{
setData(new ArrayCollection);
sendNotification( DATA_UPDATED, data );
}
//隱藏的 getter 給自己看的,順便轉換資料型態
private function get list() : ArrayCollection {
return data as ArrayCollection;
}
}
}

sendNotification( DATA_UPDATED, data );
重點在這邊,DataProxy 只負責發送 data updated Notification 出去,其他啥都不管。

2. UpdateDataCommand:
用來處理呼叫 DataProxy save and clear function 用 command。可以避免由 view component 的 Mdeiator 直接取用修改 DataProxy。
package com.mvc.control
{
import com.mvc.model.DataProxy;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.command.SimpleCommand;

public class UpdateDataCommand extends SimpleCommand
{
public function UpdateDataCommand()
{
super();
}
override public function execute(notification:INotification):void
{
var proxy:DataProxy = facade.retrieveProxy( DataProxy.NAME ) as DataProxy;
if(notification.getName() == DataProxy.SAVE_DATA){
proxy.save(notification.getBody());
}else{
// notification.getName() == DataProxy.CLEAR_DATA
proxy.clear();
}
}
}
}


資料處理完後接下來要準備製作 view component 囉!
3. TestpureMVC2.mxml
只負責發兩個 event "save" and "clear",順便提供兩個屬性給外面使用。
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" applicationComplete="facade.startup( this );" width="500" height="300">
<mx:Metadata>
[Event("save")]
[Event("clear")]
</mx:Metadata>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import com.mvc.ApplicationFacade;
private var facade:ApplicationFacade = ApplicationFacade.getInstance();

[Bindable]
public var list:ArrayCollection;

[Bindable]
public var input:String;

]]>
</mx:Script>
<mx:Label text="pureMVC 練習啪兔" fontSize="16" />
<mx:HBox width="100%" height="100%" y="30"
paddingLeft="20" paddingRight="20" paddingBottom="20">
<mx:VBox width="100%" height="100%">
<mx:Label text="Input text" />
<mx:TextInput id="inputTxt" width="100%" height="100%" text="Test pureMVC part2"/>
<mx:Button label="Save"
click="input=inputTxt.text;
dispatchEvent(new Event('save'))" />
</mx:VBox>
<mx:VBox width="100%" height="100%">
<mx:Label text="Result list" />
<mx:List dataProvider="{list}" width="100%" height="100%" />
<mx:Button label="Clear" click="dispatchEvent(new Event('clear'))" />
</mx:VBox>
</mx:HBox>
</mx:Application>


4. View component 做完就開始寫它的邏輯中介者 AppMediator
package com.mvc.view
{
import com.mvc.model.DataProxy;
import flash.events.Event;
import mx.collections.ArrayCollection;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;

public class AppMediator extends Mediator
{
public function AppMediator(mediatorName:String=null, viewComponent:Object=null)
{
super(mediatorName, viewComponent);
//接收UI的Event
app.addEventListener( "save", doClick);
app.addEventListener( "clear", doClick);
}
override public function listNotificationInterests():Array
{
//要處理啥訊息都在這邊列好
return [
DataProxy.DATA_UPDATED
];
}
override public function handleNotification(notification:INotification):void
{
//處理 data updated notification,將收到的資料送回 app.list
switch(notification.getName()){
case DataProxy.DATA_UPDATED:
app.list = notification.getBody() as ArrayCollection;
}
}
//給自己看的,重點還是轉換物件型態
private function get app():TestpureMVC2 {
return viewComponent as TestpureMVC2;
}
//當收到 click event 只將 Notification發送出去
private function doClick(event:Event):void{
switch(event.type){
case "save":
sendNotification( DataProxy.SAVE_DATA, app.input);
break;
case "clear":
sendNotification(DataProxy.CLEAR_DATA);
break;
}
}
}
}

這個 AppMediator 透過 DataProxy.SAVE_DATA and DataProxy.CLEAR_DATA Notification 跟外面溝通,如果把 SAVE and CLEAR 的常數建在別的 Class 中,你會發現 AppMediator 跟 DataProxy 一點關係都沒有,名言就是…我不認識你,你最好也不要認識我啊...XD

5. 幾乎完成啦!接下來將 ApplicationFacade 寫好:
package com.mvc
{
import com.mvc.control.StartupCommand;
import mx.core.Application;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.patterns.facade.Facade;

public class ApplicationFacade extends Facade implements IFacade
{
public static const STARTUP:String = 'startup';
public function ApplicationFacade()
{
super();
}
public static function getInstance() : ApplicationFacade
{
if ( instance == null ) instance = new ApplicationFacade( );
return instance as ApplicationFacade;
}

override protected function initializeController( ) : void
{
super.initializeController();
registerCommand( STARTUP , StartupCommand );
}

public function startup( app:Application ) : void
{
sendNotification( STARTUP, app );
}
}
}

@@ 完全沒動過的標準寫法....

6. 最後的 StartupCommand:
package com.mvc.control
{
import com.mvc.model.DataProxy;
import com.mvc.view.AppMediator;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.command.SimpleCommand;

public class StartupCommand extends SimpleCommand
{
public function StartupCommand()
{
super();
}
override public function execute(notification:INotification):void{
facade.registerMediator( new AppMediator(null, notification.getBody()) );
facade.registerProxy( new DataProxy());
//註冊 Save and Clear 對應的 UpdateDataCommand
facade.registerCommand( DataProxy.SAVE_DATA , UpdateDataCommand );
facade.registerCommand( DataProxy.CLEAR_DATA , UpdateDataCommand );
}
}
}

將 DataProxy.SAVE_DATA and DataProxy.CLEAR_DATA 指定到 UpdateDataCommand。
完工!!
這次練習的重點就是讓 Mediator and Proxy 關係更不好,當你可以弄到它們互相裝做不認識對方的時候,就是你成功的日子啊!

Comments

  1. 問一下唷^^~

    [mx:Metadata]
    [Event("save")]
    [Event("clear")]
    [/mx:Metadata]

    這段的含意是?

    如果只有
    public static const SAVE:String = "save";
    public static const CLEAR:String = "clear";

    dispatchEvent(new dispatchEvent(SAVE));
    dispatchEvent(new dispatchEvent(CLEAR));

    這樣會有問題嗎?

    ReplyDelete
  2. 嘗試了一下
    好像沒有差別呢!!!

    是我沒注意到什麼嗎?

    ReplyDelete
  3. 宣告 Metadata Event 的用意就是要給 mxml 辨認:如 Button ,你直接用 mxml 寫的時候不是可以直接 < mx:Button click="ClickEvent" .....> 這個 click 就是使用 Metadata 宣告來的...所以我上面寫在 mx:Application 是有點無聊的...

    ReplyDelete

Post a Comment

Popular posts from this blog

PureMVC for Unity

幾個月前改用 Unity 開發遊戲,到目前的心得為:組件式開發真的是很便利,但是當組件數量多到一定程度時,結構上就有點可怕,常常在某 GameObject 上掛了組件後就忘了它的存在,雖然可以使用 Singleton design pattern 來製作主要的 Manager(本人對 Singleton 並不是很熱愛),程式還是會亂到一定程度,搜尋了一些 Unity with MVC 討論,一部分的人都對實作 MVC 不是很熱絡,也許是 Unity 特有的開發環境導致。 以前開發 Adobe Flex 專案最愛用的 MVC Framework 就是 PureMVC,即使後來有更方便的 MVC Framework 的也擋不住我對它的熱愛。Unity 是沒有所謂的全域 Root Scene,所有場景都是獨立,想要將 AS3 實作邏輯套用在 Unity 上將控制項都在 PureMVC 架構中實作是有點矯情多餘。如何保持 Unity 組件開發模式,導入 PureMVC 鬆綁主要邏輯,就是這次實驗的重點。 不清楚 PureMVC 的朋友們可以到這邊參觀一下: PureMVC 我也會 PureMVC C# Standard Framework on GitHub ViewComponent 與 Mediator 整合是首要工作: 由於 Unity 沒有全域 Root Scene,如果將 new Mediator( viewComponent ) 寫在 PureMVC 架構下,即使透過 GameObject.Find 找那個對應的 GameObject 就轉了九彎十八拐,寫起來一點都不愉快,尤其考慮到場景的轉換,兩個場景中相關 Mediator 的註冊與移除處理,何況對 Unity 組件來說,能不能被打包動態載入是件重要的事。綜合以上問題點,反向思考,改由 GameObject 掛載中介組件,在 OnEnable 與 OnDisable 通知 Facade 去註冊與移除其 Mediator,一來簡化為了實作 Meditaor 掛載 ViewComponent 而對 static class GameObject 的依賴,二來也不會對 Unity 組件開發模式有太大的影響。

[Swift3] weak 與 unowned 關鍵字

雖然在 Swift 中看起來"很像"是不需要煩惱內存管理的問題,不過實際上它還是遵循著自動引用計數 (ARC) 的規則,當一個物件沒有被其他對象引用時會自動被銷毀,如果三魂七魄沒有完全回位的話,就會有個靈體留在現世的空間裡,最經典的範例如下: 閉包(Closure)引用 classClassA { typealias Complete = ()->() var name : String var onComplete : Complete? init(_ name: String){ self.name = name print("Hello I am \(self.name)") onComplete = { print("\(self.name): onComplete!") // --> 閉包引用 self, 計數 + 1 } } deinit { print("deinit: \(self.name)") } } var a : ClassA? = ClassA("A") // --> 引用計數 + 1 a = nil // 2-1 = 1 還剩下 1 所以沒辦法銷毀 ---output------- Hello I am A 由於這邊的 onComplete 宣告為 Optional, 正確的做法要連同 onComplete 一起刪除才可以被回收,若不是 Optional 則會進入無法回收狀態: var b : ClassA? = ClassA("B") b?.onComplete = nil // --> 還好是 Optional 可以設成 nil 計數 - 1 b = nil // 計數 = 0 所以被回收 ---output------- Hello I am B deinit: B 但是做人不需要煩惱太多,這時候就出動 unowned 關鍵字讓物件可以順利被回收: onComplete = { [unowned self] in print...