これを検索しましたが、これまでのところ重複を見つけることができませんでした。間違ったキーワードを使用している可能性があります...
オブジェクトに保存されている関数を一時的に変更しようとしていますが、以前の状態に戻すのに苦労しています。
このことを考慮:
// Set the options object
var options = {
success: function(){
console.log('Original Function Called');
}
}
// Save the options
$('#foo').data('bar',options);
そして、別の関数で:
// Get the options
var options = $('#foo').data('bar');
// Store the old options
var old_options = options;
// Temporarily change the success function
options.success = function(){
console.log('Temporary Function Called');
}
// Save the options
// This allows the other functions to access the temporary function
$('#foo').data('bar',options);
// Do stuff here that uses the new options
// Reset the options to include the original success function
$('#foo').data('bar',old_options);
一度だけ表示されると思っていたのですが、古いコールバックが一時的なコールバックTemporary Function Called
に完全に置き換えられているようです。success
これを回避する理由と方法を誰か教えてもらえますか?
アップデート
これで直るだろうと思ってextend
いたのですが、問題はもう少し深刻なようです。今回は実際のコードのスニペットを投稿することにしました。読む前に、次の点に注意してください。
SM
は の単なるエイリアスですjQuery
。無視してください。success
関数に提供さerror
れるパラメーター
これが私のコードです:
// Get the properties
var properties = $(form).data('autosave');
switch(parameter){
case 'save':
var old_properties = $.extend({},properties);
// Set the new callbacks if they have been supplied
properties.options.success = typeof success!=='undefined' ? success : old_properties.options.success;
properties.options.error = typeof error!=='undefined' ? error : old_properties.options.error;
// Save the properties
$(form).data('autosave',properties);
// Call the save method before setting the interval
SM(form)._as_save();
properties = $.extend({},old_properties);
// Save the old properties
$(form).data('autosave',properties);
// Clear the current interval
clearInterval(properties.interval);
// Call the save method periodically
properties.interval = setInterval(function(){
SM(form)._as_save();
},properties.options.interval);
break;
}
// Save the properties
$(form).data('autosave',properties);