2015-09-26 33 views
1

我正在嘗試使用非常酷的Bootstrap Notify插件,雖然它需要相當多的DIY樣式,但工作得非常好。爲什麼我的回調函數收到undefined作爲參數值?

除此之外,該插件的主要方法,$.notify(message, options & settings)提供了一個設置屬性的OnClose回調,在通知彈出式視窗(麪包)被關閉,不論是自然或通過單擊Dismiss圖標。

在插件的代碼調用回調,像這樣:

if ($.isFunction(self.settings.onClose)) { 
    self.settings.onClose.call(this.$ele); 
} 
在其 close功能,被稱爲當用戶關閉警報,或當其延遲時間的流逝,它自動關閉

。當我在傳入回調函數之前檢查this.$ele的值時,我發現它是一個類似jQuery的對象,表示一個元素的數組,即警報元素忙於從窗口中刪除自己。 E.I.含有該元素的數組:

<div data-notify="container" class="col-xs-11 col-sm-4 alert alert-minimalist animated fadeInDown fadeOutUp" role="alert" data-notify-position="top-right" data-closing="true" style="display: inline-block; margin: 0px auto; position: fixed; transition: all 0.5s ease-in-out; z-index: 1031; top: 20px; right: 20px;"> 
    <button type="button" aria-hidden="true" class="close" data-notify="dismiss" style="position: absolute; right: 10px; top: 5px; z-index: 1033;">×</button> 
    <span data-notify="icon"></span> 
    <span data-notify="title"> 
    </span> <span data-notify="message">Hey hey hey!</span><a href="#" target="_blank" data-notify="url"></a> 
</div> 

我使用以非常簡單的測試頁的通知插件,像這樣:

$("button").click(function() { 
    $.notify("Hey hey hey!", { 
     type: "minimalist", 
     delay: 50000, 
     onClose: function(element) { 
      console.log("Element: " + element); 
     } 
    }); 
}); 

然而,當該onClose回調被調用時,它的element參數值是undefined 。爲什麼在調用回調和執行回調代碼之間這個值變得不確定?

+0

嘗試在onClose中執行console.log($(this))以查看它是否打印出您需要的內容。 –

+0

也許'this'的範圍丟失了。我剛剛閱讀了一篇關於如何將這種方法作爲arg分配的優秀文章。 http://alistapart.com/article/getoutbindingsituations – HolyMoly

回答

1

在插件的代碼:

self.settings.onClose.call(this.$ele); 

不傳遞任何參數的onClose()回調。 .call()的第一個參數是應該爲回調設置的this指針。任何後續的參數.call()將是回調的實際參數。由於沒有,所以你尋找的將是undefined

更多信息,請參見MDN doc for .call()

所以,如果你想訪問與此呼叫相關的元素,那麼你可以使用this回調裏面。

$("button").click(function() { 
    $.notify("Hey hey hey!", { 
     type: "minimalist", 
     delay: 50000, 
     onClose: function() { 
      console.log(this); 
     } 
    }); 
}); 
+0

所以你想說的是,OP應該使用$(本)中的OnClose來獲取被關閉 –

+0

@HieuLe元素 - 是的,你是正確的 - 我加對我的回答 - thx。 – jfriend00

+0

@ jfriend00謝謝你的教育回答。直到現在我還沒有真正知道有關'call'的任何信息。我修改了插件代碼,將兩個相同的參數值傳遞給'call':'self.settings.onDismiss.call(this。$ ele,this。$ ele);'並且我的回調正是我期望的元素。 – ProfK

相關問題