【发布时间】:2015-03-03 01:58:22
【问题描述】:
最近我一直在从事一个需要我对 Symfony 后端进行大量 AJAX 调用的项目。由于每个 AJAX 调用都是针对不同的 URI 进行的,因此我最终得到了一个非常长的脚本,但包含大量 .on('event', function(){...}) 代码块,如下所示:
$(document).ready(function(){
$('.class').on('click', function(e){
e.preventDefault();
//AJAX call
这基本上是一遍又一遍地重复,但是由于选择器和要接收的数据类型略有不同,我不断地一遍又一遍地编写相同的代码块。
我一直在考虑使用构建器模式(在 JS 中甚至可能吗?)来修剪代码。我不是很擅长 javascript,所以任何帮助将不胜感激。
更新:
/**
* AJAX prototype
*
* @param options
* @constructor
*/
//set TestProtObj properties in the constructor
var AjaxProt = function (options) {
this.ajaxCallType = options.ajaxCallType;
this.targetEl = options.targetEl;
this.event = options.event;
this.method = options.method;
this.htmlFactory = options.htmlFactory;
};
//add methods to the object prototype
AjaxProt.prototype = {
init: function () {
var targetEl = this.targetEl;
targetEl.on(this.event, function(e) {
e.preventDefault();
this.ajaxCall();
})
},
modalCallback: function(successData) {
var modal = this.htmlFactory.createHtml({
title: 'Bet: Detailed View',
id: '#bet-detailed-model',
htmlType: 'modal'
});
if (successData.success = true) {
$('#content').prepend(modal);
$('#bet-detailed-model').modal({show:
true
});
} else {
$('#content').prepend(modal);
$('#bet-detailed-model').modal({
show: true
});
$('.modal-body').append(alert);
}
},
ajaxCall: function() {
var url = this.targetEl.attr('href'),
method = this.method,
ajaxCallType = this.ajaxCallType;
switch (ajaxCallType) {
case 'modalGet':
var callback = this.modalCallback();
break;
}
$.ajax({
url: url,
type: method,
success: function(data) {
callback(data)
}
});
}
};
//initialize client code
$(document).ready(function () {
// initialize new AjaxPro
var AjaxBetDetailed = new AjaxProt ({
ajaxCallType: 'modalGet',
targetEl: $('.ajax-ticket-view'),
event: 'click',
method: 'GET',
htmlFactory: new HtmlFactory()
});
//initialize concrete object
AjaxBetDetailed.init();
});
不幸的是,我的事件处理程序似乎没有绑定,因此 e.preventDefault 不起作用 - 它所做的只是点击链接。我真的不习惯以这种方式编写课程,因此将不胜感激。
更新 2:
我还在 jsfiddle 中编写了一个概念证明类,它试图复制我想要实现的行为。它也无法绑定事件处理程序 - 所以这一定是问题所在。我好像没办法解决。
JSFiddle:Click Me Please!
【问题讨论】:
-
您能否给我们展示一整块(或两块)以更好地展示它们之间的差异?
-
需要查看模式以便提供任何建议
-
好吧,伙计们,我终于摆脱了为这种模式编写代码的懒惰,因为我懒得继续复制/粘贴我糟糕的意大利面条代码。
标签: javascript jquery ajax oop