Reputation: 21206
var viewmodel = service.createCustomer();
is the way I call the requirejs module.
How do I have to create a deferred object that my createCustomer returns the CreateCustomerViewModel which is created inside the service call?
define(['viewmodels/CreateCustomerViewModel'],function (CreateCustomerViewModel) {
function createCustomer() {
$.getJSON('Customer/Create')
.done(function (response) {
return new CreateCustomerViewModel(response);
})
.fail(function (error) {
alert(error);
});
}
return {
createCustomer: createCustomer
};
});
Upvotes: 4
Views: 5696
Reputation: 140050
.then()
instead of .done()
to modify the payload.createCustomer
method return the modified payload.Your module definition becomes:
function createCustomer() {
return $.getJSON('Customer/Create')
.then(function (response) {
return new CreateCustomerViewModel(response);
});
}
return {
createCustomer: createCustomer
};
Use as:
customerCreator.createCustomer()
.done(function (model) {
// yay! let's use this model
})
.fail(function () {
console.error("Cannot create customer");
});
You should also move the .fail()
handling outside, as high up in the application as possible, so that the wording in your error message can have a more accurate context.
P.S. As a nitpick, shouldn't you be using a POST request instead of a GET to create an entity?
Upvotes: 5