1
我試圖調用JQuery UI小部件的「自定義」方法,並通過this
/self/context進行測試。但上下文沒有傳遞給該方法。當我從其方法undefined
中檢查this
。在對象方法上使用.call()不會傳遞上下文
短例子是我請用下面的代碼的方法,包括:
widget.myWidget('option', "classChangeCallback").call(widget);
當我檢查this
從內側classChangeCallback
它是undefined
。以下是您可以複製的問題的示例。
(function ($) {
$.widget("MY_NAMESPACE.myWidget", {
\t options: {
\t \t classChangeCallback: function() {
\t \t \t // When this callback is called via click evt: this.element is defined
\t \t \t // When this callback is called using .call, .apply: this.element is undefined
\t \t \t console.log(this.element);
\t \t \t
\t \t \t var newEle = $('<div><p>New Element</p></div>')
\t \t \t \t .appendTo(this.element)
\t \t \t return newEle;
\t \t }
\t },
\t _create: function() {
\t \t this._super("_create");
\t \t // Bind to click event as an example only: in my project this
\t \t // callback is actually called when an elements classes change
\t \t this.element.click(this.options.classChangeCallback.bind(this));
\t },
});
})(jQuery);
// .............
$(document).ready(function() {
\t var widget = $('[data-type="foo"]').myWidget();
\t // In my testing I want to call the function to test it
\t widget.myWidget('option', "classChangeCallback").call(widget);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<div data-type="foo" style="min-height:100px; background-color: green;">
\t \t
\t \t <p>
\t \t \t Bar
\t \t </p>
</div>
是否'widget.myWidget( '選項', 「classChangeCallback」)'返回你的期望? –