Summary
Instead of calling WebApi straight from a Web Forms User Control, I have created JS class which contains functions returning jQuery AJAX requests. The control would instantiate the class and call these functions, which would allow me to separate the code that calls the API from my control.
Is this the best approach? What down-falls could there be later?
Implementation
MyService.js
Assume my WebApi controller is called MyServiceController. The client-side JS class would be:
class MyService
{
// Example method to call
start = function(userId) {
return $.ajax({
url: '/api/myService/start',
type: 'POST',
data: {
id: userId
});
}
// Another example method
stop = function() {
return $.ajax({
url: '/api/myService/stop',
type: 'POST'
});
}
}
MyCode.ascx
This will then be consumed from the web forms control as so:
// Instantiate the class
var let api = new MyService();
// Assume document has loaded and add click-handler
var someId = 1;
// Call Start
$('.myService-start').click(function(){
api.start(someId)
.done(function(){
console.log('start completed');
})
.fail(function(){
console.log('start failed');
});
});
// Call Stop
$('.myService-stop').click(function(){
api.stop()
.done(function(){
console.log('stop completed');
})
.fail(function(){
console.log('stop failed');
});;
});
<span class"myService-start">Start</span>
<span class"myService-stop">Stop</span>
Question
Am I following a bad pattern? Will this lead to a code-smell later on?
Please let me know if there's a better way to implement this