🔧
JSOM の executeQueryAsync で使われている Function.createDelegate について
JSOM のサンプルでは、Function.createDelegate がよく使用されています。今回の記事では、この Function.createDelegate について解説します。
引数に this を渡しているため、JavaScript の this の扱いに関する課題を解決できることが想像できます。Function.createDelegate を利用することで、this の参照先を明示的に指定できます。
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<script type="text/javascript">
var obj = {
web: null,
retrieveTitle: function () {
var ctx = SP.ClientContext.get_current();
this.web = ctx.get_web();
ctx.load(this.web);
ctx.executeQueryAsync(this.onSuccess); // NG
ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess)); // OK
},
onSuccess: function () {
alert(this.web.get_title());
}
};
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
obj.retrieveTitle();
});
</script>
</asp:Content>
なお、Function.createDelegate は MicrosoftAjax.js に定義されています。
Discussion