私は jQuery プラグインを作成し、それらを AJAX と統合しています。私は脂肪を減らし、基本に集中しています。
(function($)
{
function MyPlugin(el, options)
{
this.element = $(el);
this.myInput = false;
this.options = $.extend(
{
onSave:function(){}
}, options);
this.initialize();
}
$.fn.myPlugin = function(options)
{
var control = new MyPlugin(this.get(0), options);
return control;
};
MyPlugin.prototype =
{
initialize:function()
{
var me = this;
//specifics shouldn't really matter
//it creates some HTML to go inside the element
//within that HTML is an input, which I can successfully invoke keyup:
me.myInput.keyup(function(event)
{
if(keyPressIsEnter(event)
me.saveFunction();
});
},
saveFunction:function()
{
var value = this.myInput.val();
this.options.onSave(value);
//CURRENTLY I CALL SUCCESS ANIMATION
successAnimation();
},
successAnimation:function()
{
//do something to the markup within element for success
},
failureAnimation:function()
{
//do something to the markup within element for failure
}
};
})(jQuery);
そして、divがあり、プラグインを次のように使用するように設定したとしましょう:
$("myDiv").myPlugin({onSave:function(value){myAjaxSaveFunction(value);});
このセットアップでは、プラグイン、保存機能、およびアニメーションがすべて機能します (エラーが発生しない場合)。ただし、myAjaxSaveFunction は非同期であり、成功または失敗のいずれかを返す可能性があります。現在、成功アニメーションを呼び出すプラグイン内に保存機能があります。myAjaxSaveFunction が true/false を返すようにした場合、(理論的には) プラグイン内でその戻り値を使用して、成功または失敗を実行するかどうかを判断できますが、関数が非同期であるかどうかは判断できません。
では、このシナリオは通常どのように処理されるのでしょうか? 再利用するには、オプションのコールバックとしてデータを処理する関数をカスタマイズできる必要がありますが、関数の結果に基づいて成功/失敗のアニメーションを実行するかどうかをプラグインで待機する必要があります (これは非同期である可能性があります)。そうでない場合もあります)。
@ケビンB:これを提案していますか?
saveFunction:function()
{
var value = this.myInput.val();
var success = this.options.onSave(value);
if(success)
successAnimation();
else
failureAnimation();
},
this.options.onSave 関数が実行されている間、これは if ステートメントにすぐに落ちませんか?