2015-10-26 53 views
0

我有這個全局函數接受配置對象來顯示參數$.dialogeventHandler結束時的Javascript調用函數

這是源

function close() { 
    $(this).dialog('close').remove(); 
}; 
function modal(options) { 
    var opt = { 
     'modal': true, 
     'width': 400, 
     'close': close, 
     'buttons': options.buttons || { Ok: close } 
    }; 
    var dialog = $('<div>') 
    .attr('id', 'dialog') 
    .attr('title', options.title || 'Info') 
    .append($('<p>').text(options.content)); 
    $('body').append(dialog); 
    dialog.dialog(opt); 
} 

但我希望讓更容易通過實現一種小提醒對象的,以便不寫醜和日誌配置對象,還挺喜歡說話的方法來調用它$.get()$.post()方法。

每次創建和銷燬dialog的原因是,這樣做是非常簡單的,而不是重寫現有的。

我到目前爲止的問題是,我必須記得在每個eventHandler結束時調用close函數。

所以我提醒對象看起來像這樣

var alert = { //the name is work in progress, don't worry 
    info: function(text, okHandler){ 
     modal({ 
      content: text, 
      buttons: { 
       Ok: okHandler //here I want to append automatically the close() function 
      } 
     }); 
    }, 
    error: ... 
}; 

,我想這樣稱呼它

alert.info('Success!', function(){ 
    doSomething(); 
    //then close without me having to remember to do so 
}); 

是我想達到什麼可能?我一直在尋找進入Function.prototype.call()方法來做到這一點,但它的其他用途

+0

這是很難理解的基本問題,你能解釋你的問題從一個通用的例子沒有明確的項目上下文? –

回答

0
var alert = { //the name is work in progress, don't worry 
    info: function(text, okHandler){ 
     modal({ 
      content: text, 
      buttons: { 
       Ok: function() { 
        okHandler.apply(this); 
        //here I want to append automatically the close() function 
        close.apply(this); 
       } 
      } 
     }); 
    }, 
    error: ... 
}; 
+0

'okHandler()'中'$(this)'的範圍是一樣的嗎? – fra9001

+0

看到我對「close」行的改變 – Igor

0

這個問題是竊聽我,因爲它似乎是我還是寫不雅代碼。我想現在我有了正確的答案,@Igor讓我走向了正確的方向。

function handler(/*callback*/) { 
    var callback = arguments[0]; 
    return function() { 
     if (callback != null) callback.apply(this); 
     close.apply(this, arguments); 
    }; 
} 

function info(text, okHandler){ 
    modal({ 
     title: 'Info', 
     content: text, 
     buttons: { 
      Ok: handler(okHandler), 
      Close: close 
     } 
    }); 
} 

handler()返回function的範圍將是jQuery事件處理程序中的DOM元素,close()將被默認調用,但將不會被寫入多次。

此時,您甚至可以撥打handler()而不是通過close(注意括號)並獲得相同的結果。

相關問題