我想知道是否可以在视图模型中的另一个方法中调用方法
在我的附件中:我有一个ajax方法来显示所有客户
attached: function () {
$.ajax({
type: "GET",
url: "/api/listusers/GetContractorList",
dataType: "json",
contentType: "application/json; charset=utf-8",
headers: appsecurity.getSecurityHeaders(),
success: function (result) {
if (result != null) {
var mappedContractorList = $.map(result, function (item) {
return new GKContractorObj(item);
});
viewmodel.ContractorList(mappedContractorList);
tableObj = $('#tblContractorsList').DataTable();
}
},
failure: function (error) {
logger.logError('Failed to contractor list', 'Error', null, true);
}
})
我想调用附加的方法:在另一个数据绑定方法中的函数
showGKContractors:
function () {
//Some Logic
//Call to url (attached:method): "/api/listusers/GetContractorList"
(without having to rewrite code)
}
我该如何解决这个问题?
答案 0 :(得分:0)
使用共享逻辑最好的做法是将其移出视图模型,并将其放在可供两个视图模型使用的共享类中。
如果您实际上试图在另一个视图模型中触发某些内容,那么您应该使用事件或消息来执行此操作。有几个图书馆支持这个。
答案 1 :(得分:0)
是的!只需将您想要在多个地方调用的附加内容的代码部分移动到一个对您的两个视图模型都可见的全新功能中,例如
makeAjaxRequest: function () {
///1. the code you want to move from inside your attached function
}
然后将新功能调用为附加功能和showGkContractors
attached: function () {
makeAjaxRequest();
///2. all the other code you don't want to move from attached
}
showGKContractors: function () {
//1. Some Logic
//2. makeAjaxRequest();
}
如果附加的和showGKContractors都在同一个.js文件中,则可以在页面顶部定义新函数,或者如果需要,可以将其放在单独的脚本文件中并通过命名空间引用
例如,在GKContractors上方的网页上包含的单独文件中,附加文件包含带有此脚本的文件
(function (scope) {
scope.makeAjaxRequest: function () {
///1. the code you want to move from inside your attached function
///2. all the other code you don't want to move
}
})(window.SharedNameSpace);
然后在你的attach和showGKContractors文件中你可以调用makeAjaxRequest函数 通过调用
window.SharedNameSpace.makeAjaxReuest();