標籤:c style class blog code java
PromiseEvent
基於事件和promise的回調管理,類似於jquery的callbacks,但具有結果傳遞,優先順序,事件參數,promise控制等功能
介面方法
var events = st.promiseEvent(mode);events.add(name,function(e,arg,……){ },priority,eventMode)event.fire(arg,...);
參數說明
mode :once和callback兩種模式,(callback模式不會加入事件參數)
e.stopProgation() 阻止後續回調
event.add(name,fn,priority,eventMode) 添加事件回調, name :加入的事件回調名稱; priority :權重設定 ;eventMode :加入的事件模式;once;
event.fire(arg,,,,) 執行事件回調
event.fireWith(context,[args]) 使用上下文回調
event.has(name) 根據回調名稱判斷是否登入回調
event.remove(name) 根據名稱刪除回調
event.clear() 清除所有回調
e事件參數
e.result 上一個回調的結果
e.remove() 刪除當前回調
e.promise() 返回契約
e.resolve() 解決契約
e.reject() 拒絕契約
使用範例
普通方式
var calls = st.promiseEvent(), result = []; //測試使用once模式,執行一次既銷毀 calls.add(‘call1‘, function(e, text) { result.push(text+‘1‘); },"once") calls.add(‘call2‘, function(e, text) { //效果同“once” e.remove() result.push(text+‘2‘); }) //執行,結果 [call1,call2] calls.fire(‘call‘);
權重,預設權重為0,可以通過st.conf({defPriority:100})來設定,相同權重先入先出
result = []; //權重 calls.add(‘p‘, function(e, text) { result.push(‘def‘); }) calls.add(‘p10‘, function(e, text) { result.push(10); },10) calls.add(‘p50‘, function(e, text) { result.push(50); },50) calls.add(‘pDef‘, function(e, text) { result.push(‘def2‘); }) //執行,結果 [50,10,def,def2] calls.fire();
stopProgation,停止後續回調
//stopProgation,停止後續回調 calls.add(‘stop‘,function(e){ e.stopPropagation(); result.push("stop"); },20) //執行,結果 [50,stop] calls.fire();
結果傳遞,promiseEvent回將return的結果或者resolve的非undefined的結果記錄下來並向下傳遞;
//result傳遞模式 calls.add(‘c1‘, function(e, text) { return text + "-c1"; }) calls.add(‘c2‘, function(e, text) { return e.result + "-c2"; }) calls.add(‘c3‘, function(e, text) { return e.result + "-c3"; }) //執行,結果 test-c1-c2-c3 calls.fire(‘test‘);
Prmose模式,
可以與jquery的promise結合使用
$.when(calls.fire()).done(function(result){
})
//清除回調 calls.clear(); result = []; //promise模式 calls.add("c1", function(e) { setTimeout(function() { result.push("c1"); e.resolve(); }, 100); return e.promise(); }); calls.add("c2", function(e) { result.push("c2"); }); //執行,結果 [c1,c2] calls.fire();
mode設定,once(執行及銷毀)和callback(簡單回調)
//callback模式 & once模式 var calls2 = st.promiseEvent("callback once"); //callback不存在e事件參數,只是具有見的回調管理 calls2.add(‘c1‘, function(text) { return text + "-c1"; }) //執行第一次,結果 test-c1 calls2.fire(‘test‘); //執行第二次,因為once模式,結果 undefined calls2.fire(‘test‘);
更多的例子請參考smartjs上的測試案例