Server
在客戶端可以用JavaScript訪問的方法必須用@ExtDirectMethod註釋。註釋方法的bean必須是Spring管理的bean。
@Service
public class TestAction {
@ExtDirectMethod
public String doEcho(String message) {
return message;
}
@ExtDirectMethod
public int anotherAction() {
return 1;
}
}
如果方法需要訪問服務器對象,如請求和響應,添加參數的方法簽名。
@ExtDirectMethod
public String doEcho(String message, HttpServletRequest request) {
//do something with the request
return message;
}
ExtDirectSpring支持的服務器對象參數:
HttpServletResponse
HttpServletRequest
HttpSession
Locale
Principal
Parameters annotated with @RequestHeader (since 1.1.0)
服務器對象參數可以添加任意順序
@ExtDirectMethod
public String doSomething(HttpServletResponse response, int fromClient1,
HttpServletRequest request, int fromClient2,
Locale locale, int fromClient3) {
//do something here
}
客戶端方法看不到服務器對象參數,調用doSomething方法示例如:testAction.doSomething(1, 2, 3, callback)。
類庫也支持 @DateTimeFormat和@NumberFormat註釋。
@ExtDirectMethod
public Map<String, Object> aMethod(@DateTimeFormat(iso = ISO.DATE_TIME) Date aDate,
@NumberFormat(style = NumberFormat.Style.PERCENT) BigDecimal percent) {
...
}
Client
Spring bean的name是客戶端action的名字。如testAction.doEcho('ping', callback)將會調用服務器端Spring bean testAction的方法doEcho。調用服務器的方法通常是異步因此需要一個回調函數,回調函數將會被調用有返回的時候。回調函數是調用服務器方法的最一個參數。如果服務器方法一個參數沒有,回調函數是唯一參數。testAction.anotherAction(callback)。最後一個參數也有可能是回調函數執行的作用域,testAction.doSomething(1, 2, 3, callback, this)。
參數的順序和個數必須跟服務器方法簽名一致(服務器對象除外)。
回調函數不是必須的可以省略。
Callback function
var callback = function(result, e) {
// do something with the result
};
回調函數會被調用當服務器端返回結果或拋出一個異常。一個Ext.Direct回調函數被調用,帶有兩個參數:
result 這個參數包含服務器方法返回的數據。
e 一個Ext.Direct.RemotingEvent (Ext JS 3) 或 Ext.direct.RemotingEvent (Ext JS 4.x and Sencha Touch 2)
event對象有一些有用的屬性和方法:
status true 如果方法調用成功,false如果方法調用失敗
result 包含同返回結果一樣數據
type rpc或exception 如果異常發生
action bean的name例如‘testAction’
method 方法的名字 (*'doEcho'*)
tid 事務id
getTransaction() 獲得調用服務器方法的事務。這個對象包含一些信息,如transaction.args包含方法調用時的參數。
Events
Direct Manager支持兩類事件event和exception。event在調用服務器方法返回後觸發。exception在發生異常時觸發。可以很容易監聽這些事件通過添加監聽到Ext.direct.Manager。
//Ext JS 4.x and Sencha Touch 2
Ext.direct.Manager.on('event', function(e) {
//do something here
});
Ext.direct.Manager.on('exception', function(e) {
//do something here
});
Examples
- http://demo.rasc.ch/eds/extjs3/simple.html
- http://demo.rasc.ch/eds/extjs3/direct.html
- http://demo.rasc.ch/eds/extjs41/direct.html
- http://demo.rasc.ch/eds/extjs42/direct.html