我有很多javascript函数,我想通过逻辑将它们分离成多个javascript文件。问题是,我所有的ajax函数urls都是由剃刀生成的。
$.get('@Url.Page("Index","ViewReferenceRecordsPartial")', { productionRecordId: productionRecordId }, function (response) {
$('#details').html(response)
stopLoading(element);
})我如何将这样的函数保存在js文件中?
更新
这里有一个临时解决方案,直到有了一个更易于维护的解决方案,使用数据属性非常快速。
在js文件中,我有一个函数
function viewReferenceRecords(element, productionRecordId) {
startLoading(element);
$.get($(element).data('url'), { productionRecordId: productionRecordId }, function (response) {
$('#details').html(response)
stopLoading(element);
})
}在我的桌子上我有一个按钮来调用这个函数
<button data-url="@Url.Page("Index","ViewReferenceRecordsPartial")" onclick="viewReferenceRecords(this, @Model.Id)">Details</button>它非常简单和简单,只需将由剃刀生成的Url存储在元素上的数据属性上,并将其传递给js文件中的函数,并检索在数据属性上生成的字符串。
发布于 2019-11-30 19:01:35
我通常使用显示模块模式来处理类似的事情。你可以在这里读到:https://gist.github.com/zcaceres/bb0eec99c02dda6aac0e041d0d4d7bf2
这有点像名称空间,但在JavaScript中。然后你可以输入参数。我会这样做:
JS文件
var MeaningfulModuleName = MeaningfulModuleName || (function () {
var _partialUrl = null;
return {
init: function (partialUrl) { _partialUrl = partialUrl; },
loadPartial: function (targetSelector, productionRecordId) {
$.get(_partialUrl, { productionRecordId: productionRecordId }, function (response) {
$(targetSelector).html(response);
// ...
}
}
}
});然后在您的剃须刀视图中,在页面底部创建一个脚本标记,如下所示:
<script type="text/javascript">
$(document).ready(() = {
MeaningfulModuleName.init(@'Url.Page("Index", "ViewReferenceRecordsPartial")');
// Some event occurs
MeaningfulModuleName.loadPartial('#details', productionRecordId);
}
</script>对于这个特定的JS文件,无论名称是什么,MeaningfulModuleName都是有意义的。
这为我解决了它,我认为它使JS看起来更干净一些。一切都被组织成“模块”。另外,如果代码不能很好地工作,我很抱歉。我在手机上写的。:)
https://stackoverflow.com/questions/59119193
复制相似问题