【发布时间】:2019-11-09 04:38:54
【问题描述】:
我有许多对 json 端点的调用,看起来像这样。这是在 Vue 组件的上下文中,但实际上它并不重要。所有这些处理程序所做的就是显示带有成功/错误的引导消息,所有智能都在服务器中。
所以它与所有 console.log("it worked!") 处理程序并没有什么不同,只是我的处理程序需要额外的参数。
//The Vue component
let myVue = this;
axios.post(this.action_url, qs.stringify(data), config)
.then(function (response) {
// it's a bit more complicated as it looks at response contents
// for the actual message
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
});
})
.catch(function (error) {
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "failure");
});
其他地方...
let myVue = this;
axios.post(another_url, qs.stringify(data2), config2)
.then(function (response) {
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
});
.catch ....
})
我只想编写一次响应和错误处理程序并重用它们。但是,因为我需要从我的执行上下文中知道一些东西,在这种情况下是myVue,我不能只导入一个函数并传递响应,或者我错过了什么?
function handleResponse(response){
// ???????? I need extra contextual variables, not just response
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
};
如果可行,我可以用作
axios.post(this.action_url, qs.stringify(data), config)
.then(handleResponse(response))
.catch(someErrorhandler(error));
而不是每次都以完全相同的内容重复闭包。
来自 Python,我想也许 curry(为函数调用预先分配一个参数,在这种情况下是 myVue 或 {myVue: myVue})可以做到,但什么是惯用的 JS 实现方式处理程序重用,如果处理程序相同?任何使用内置 es6 的东西都比引入像 Lodash 这样的额外依赖项更受欢迎。
【问题讨论】:
-
以及如何在组件A 上传递
myVue?还有一个myVue在 componentB 上?
标签: javascript promise axios