Yii2 Html助手与yii.js协同机制
Yii2框架内置了Html、Url、Json等多种辅助类,极大简化了开发流程。其中Html类在处理视图层时尤为常用,其优势不仅在于生成标准的HTML标签,更在于能与框架自带的静态资源文件yii.js协同工作,便捷地发起Post请求。
Yii2将常见功能进行了高度封装,开发者只需调用相应方法即可快速实现需求。例如,要在页面中添加一个删除按钮,点击后弹出确认框并发送Post请求,若不使用Yii2的Html类和yii.js,则需手动编写大量jQuery或原生JavaScript代码;而使用Yii2仅需少量配置即可完成。
// html代码
<?= Html::a(
'删除',
[
'delete',
'id' => $id,
],
[
'data' => [
'confirm' => '你确定要删除吗?',
'method' => 'post',
],
]
)
?>
// html代码
上述配置最终会在页面中渲染出如下HTML结构:
删除
用户点击该按钮时会触发确认对话框,确认后自动执行Post请求。值得注意的是,整个过程中并未编写任何JavaScript代码,那么这一行为是如何被触发的呢?
Yii2框架屏蔽了底层实现细节,Post请求的核心逻辑封装在yii.js文件中。在该文件中,定义了全局window.yii对象,并初始化了其initModule方法以启动相关模块。
window.yii = (function ($) {
var pub = {
// 定义了处理事件的方法,比如下面这个:
confirm: function (message, ok, cancel) {
if (window.confirm(message)) {
!ok || ok();
} else {
!cancel || cancel();
}
},
handleAction: function ($e, event) {
var $form = $e.attr('data-form') ? $('#' + $e.attr('data-form')) : $e.closest('form'),
method = !$e.data('method') && $form ? $form.attr('method') : $e.data('method'),
// 其他省略
},
// 其他省略
};
// 初始化模块
initModule: function (module) {
if (module.isActive !== undefined && !module.isActive) {
return;
}
if ($.isFunction(module.init)) {
module.init();
}
$.each(module, function () {
if ($.isPlainObject(this)) {
pub.initModule(this);
}
});
},
// 初始化方法
init: function () {
initCsrfHandler();
initRedirectHandler();
initAssetFilters();
initDataMethods();
},
return pub;
})(window.jQuery);
window.jQuery(function () {
window.yii.initModule(window.yii);
});
在此初始化过程中,initDataMethods()函数会被调用,进而注册pub.handleAction作为事件处理器。
function initDataMethods() {
var handler = function (event) {
var $this = $(this),
method = $this.data('method'),
message = $this.data('confirm'),
form = $this.data('form');
if (method === undefined && message === undefined && form === undefined) {
return true;
}
if (message !== undefined) {
$.proxy(pub.confirm, this)(message, function () {
pub.handleAction($this, event);
});
} else {
pub.handleAction($this, event);
}
event.stopImmediatePropagation();
return false;
};
// handle data-confirm and data-method for clickable and changeable elements
$(document).on('click.yii', pub.clickableSelector, handler)
.on('change.yii', pub.changeableSelector, handler);
}
handleAction方法负责读取前面生成的a标签上的data属性值,并将其传递给handlerAction进行后续处理。handlerAction通过动态构建一个Form元素来处理各类请求,最后通过触发submit事件来完成数据提交。
// 其他省略
$form = $('', {method: method, action: action});
var target = $e.attr('target');
if (target) {
$form.attr('target', target);
}
if (!/(get|post)/i.test(method)) {
$form.append($('', {name: '_method', value: method, type: 'hidden'}));
method = 'post';
$form.attr('method', method);
}
if (/post/i.test(method)) {
var csrfParam = pub.getCsrfParam();
if (csrfParam) {
$form.append($('', {name: csrfParam, value: pub.getCsrfToken(), type: 'hidden'}));
}
}
$form.hide().appendTo('body');
// 其他省略
总结而言,虽然使用框架能大幅提升开发效率,但长期依赖可能导致对基础技术的遗忘。深入理解框架背后的原理,有助于在任何技术栈下都能清晰掌控代码行为,避免陷入困惑。