gpt4 book ai didi

javascript - 将类方法绑定(bind)到类外绑定(bind)的事件处理程序中的 AJAX 成功回调

转载 作者:行者123 更新时间:2023-11-30 17:43:41 25 4
gpt4 key购买 nike

我的问题:

我创建了一个 JavaScript 类,供我们的开发团队在我们的网站上使用。它本质上是一种网格/表格结构的功能,允许用户选择项目并使用提供的操作按钮对这些项目执行操作。

操作按钮工作流程:
  • 用户点击操作按钮
  • 出现弹出窗口:“您确定要对这些项目执行此操作吗?”
    • 用户点击"is":进行 AJAX 调用并在 AJAX 成功时关闭弹出窗口。
    • 用户点击“否”:弹出窗口关闭。

现在,这些操作按钮由我们的开发人员在每个需要它的页面上单独绑定(bind)到 jQuery 中。任何给定的页面都可以有一些事件绑定(bind)。

成功完成任何这些操作后,我想从任何给定实例运行 Grid.afterActionComplete()我想在 AJAX 成功回调操作中运行 Grid.afterActionComplete()我知道我可以在我的类中公开(返回)afterActionComplete并让开发人员自己运行该功能,但这并不理想。

我的要求:

  • 希望将开发人员的额外代码量保持在最低限度
  • 许多 AJAX 请求可以从任何给定页面发出(一些来自非操作按钮),因此使用全局 ajaxSuccess 事件不一定有效。另外,我不愿意使用具有全局范围的事件。

我的问题有两个方面:

  1. 如何将 Grid.afterActionComplete() 动态绑定(bind)到任何给定操作的 AJAX 成功回调? (如果可能的话)
  2. 在实例化时如何最好地将操作绑定(bind)合并到 Grid 类中以进一步封装我的代码?

我的示例代码:

/* [START] Pre-existing code */
var Grid = function(gridID){
var gridID = $(gridID),
afterActionComplete = function(){
// Ideally, I'd like to bind the function here
},
refresh = function(){
// Refresh grid
},

return {
refresh : refresh
}
}

var popup = function(){
$('.popup').show();
// Pops up a window with an Action button and Cancel button
// Just a placeholder to help explain concept
}
/* [END] Pre-existing code */



/*
[START] Dev defined code
Devs will be creating these event bindings across the
site.
*/
var myGrid = new Grid("#grid1");

$('#actionPopupButton').click(function(){

popup();

$('.popup #actionButton').click(function(){

$.post( "ajax/test.html", function( data ) {

myGrid.refresh();

$('.popup').hide();

// I'd like to inject Grid.afterActionComplete() here
// Maybe create custom event and trigger() it here?
// Ideally, I would love to not require the Devs insert additional code hre, but I'm not sure that's possible

});

});

});
/* [END] Dev defined code */

我已经思考这些问题一个星期左右了,希望有任何建议可以帮助我解决这个问题。谢谢!

最佳答案

假设所有“开发人员代码”都非常相似,我认为理想情况下您会希望让开发人员传递适当的参数,而不是创建一堆非常相似的代码。

例如,如果您将 popup 方法作为 Grid 的一部分,并将 url 和回调传递给该函数,您可以做一些事情像这样:

popup = function(url, callback){
var that = this;

$('.popup').show();

$('.popup #actionButton').click(function(){

$.post( url, function( data ) {

// call the passed in callback
callback(data);

// do your post-callback stuff
that.refresh(); // assuming this happens in every callback

$('.popup').hide(); // assuming this happens in every callback

that.afterActionComplete();
});
});
}

那么您的示例开发人员代码将变成这样:

var myGrid = new Grid("#grid1");

$('#actionPopupButton').click(function(){

myGrid.popup("ajax/test.html", function(data){
// do instance-specific stuff here
});

});

关于javascript - 将类方法绑定(bind)到类外绑定(bind)的事件处理程序中的 AJAX 成功回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20553468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com