var Model = function() {
function checkStatus(){
JsonClient.onload = function() {
};
JsonClient.onerror = function(e) {
};
}
}
I know the error handler would be called when my request parameter is wrong or may be even if the service is down too.
But is there any way i can check my service is down at first place before sending the data.
Related
This is the way I'm populating the attribute of my model:
this.model.set('questionAnswers', arrQuestions);
Now on submit, I check if model is valid:
if (this.model.isValid()) {
this.model.save(null, { success: this.gradingQuestionsSuccess, error: this.gradingQuestionsFailed });
}
Validations works like this:
validate: function (attr, options) {
var error = null;
if (attr.questionAnswers.length < this.cntQues) {
this.trigger('empty:answers');
error = 'Please answer all the questions.';
}
return error;
}
And service call is:
url: function () {
var url = Application.getConfig("url") + "/";
url += Application.getConfig("v2path3") + "/account/submitGradingQuestions";
}
return url;
}
The model is valid and the values are set in it on Submit, but it's not sending it in the Request Payload.
Can anyone please help me understand why this is happening? Thanks in advance!
Backbone does not observe the changed attributes and sync on save(null) automatically. What you need is pass attributes to Model.save method that makes set under the hood here or here depending on wait option's property. So you just need the following:
var data = {questionAnswers: arrQuestions};
this.model.save(data, {
success: this.gradingQuestionsSuccess,
error: this.gradingQuestionsFailed
});
You also don't need invoke validation manually because it's get invoked in save method also.
I believe this has to do with the way JS Closures work, but I am not totally sure. I am using an AngularJS service to manage the life-cycle of a model that is used within my application. The service uses a combination of fetch() and save() to run GET and POST requests get and update the model from an API. After I fetch() the object, I attempt to place the result into an object sitting in the service where it can be fetched later on. My problem, is that after a successful save(), I take the result and place it into the same object to essentially "update" the object that is on the client with the correct object that is on the server (hence the result of the POST is just an echo of the payload if all is successful).
The problem is that my object is not persisting, and all subsequent calls to save() contain a "stale" object that is not completely updated.
Here is my service:
app.factory('MailboxSubscription', function (API, $q, $stateParams, $rootScope) {
var Subscription = null; //THIS IS MODEL THAT I TRY TO UPDATE CONSTANTLY
var isBusy = false;
var service = {};
var deferred;
var defaultFailure = function(res){
}
service.fetch = function (success, force, failure) {
if(!failure){ failure = defaultFailure;}
if(isBusy){
deferred.promise.then(success, failure);
return deferred.promise;
}else{
deferred = $q.defer();
}
if(Subscription && !force){ // ONCE THE MODEL HAS BEEN FETCHED ONCE, IT STAYS IN MEMORY AND ALL SUBSEQUENT CALLS WILL SKIP THE API CALL AND JUST RETURN THIS OBJECT
deferred.resolve(Subscription);
}else{
//Make the API call to get the data
//Make the API call to get the data
if(typeof(success) === 'function'){
var ServiceId = $stateParams.serviceId;
}else{
var ServiceId = success;
}
isBusy = true;
API.Backups.O365.Exchange.get({id : ServiceId || $stateParams.serviceId}, function(res){
isBusy = false;
if(res.success){
Subscription = res.result; // ON A FIRST-TIME FETCH, THIS API CALL IS USED TO GET THE MODEL
deferred.resolve(Subscription);
}else{
deferred.reject(res);
}
}, function(res){
isBusy = false;
deferred.reject(res);
});
}
deferred.promise.then(success, failure);
return deferred.promise;
}
service.save = function(success, failure){
if(!failure){ failure = function(){};}
if(!success){ success = function(){};}
var deferred = $q.defer();
API.Backups.O365.Exchange.update({id :$rootScope.ServiceId || $stateParams.serviceId}, Subscription, function(res){
if(res.success){
Subscription = res.result; // AFTER AN UPDATE IS MADE AND THE OBJECT IS SAVED, I TRY TO SET THE RESULT TO Subscription.
deferred.resolve(res);
}else{
deferred.reject(res);
}
}, function(res){
deferred.reject(res);
});
deferred.promise.then(success, failure);
return deferred.promise;
}
service.get = function(){
return Subscription;
}
return service;
});
So the problem appears to stem from trying to use Subscription as a centralized resource for storing the model, but the model is not updating correctly.
If you are looking to have that Subscription model updated throughout the service, I'd suggested when you call MailboxSubscription.fetch() and MailboxSubscription.save()in your controller, you use MailboxSubscription.get() in the .then() method of your calls.
// get initial value of Subscription model
$scope.Subscription = MailboxSubscription.get();
// let's fetch
MailboxSubscription.fetch().then(
// callback
function() {
// let's get the updated model
$scope.Subscription = MailboxSubscription.get();
},
// errback
function() {
// handle error
}
);
// let's save
MailboxSubscription.save().then(
// callback
function() {
// let's get the updated model
$scope.Subscription = MailboxSubscription.get();
},
// errback
function() {
// handle error
}
);
Also, I've created a working jsfiddle simplifying your use case. It works fine. Maybe there is something that can be gleamed from that (I am using $timeout to spoof your API calls).
I am struggling to solve this issue. Please look into my code below.
function GenericFormHandler(templateId, webService) {
this.templateId = templateId;
this.webService = webService;
}
GenericFormHandler.prototype.process = function(form, success, failure) {
var request= form.serializeArray();
this.webService(request,
function(data) {
success(data);
},
function(status) {
failure(status);
});
};
I am getting error at this.webService. I am running below function with
function createAccount() {
var form = $("#login");
$(form).validationEngine();
if (!$(form).validationEngine('validate'))
{
return false;
}
var handler = new GenericFormHandler('#template','$.ws.userSignUpRequest');
handler.process(form, function() {
window.location.href = "home.html";
}, function(error) {
});
}
;
I am accessing webService property in method process but it giving me error as property of an object is not a function. How to solve this error?
$.ws.userSignUpRequest is this the reference of the function , then pass it with out the string
var handler = new GenericFormHandler('#template', $.ws.userSignUpRequest);
In your code this.webService is set to a string. A string is not a method which can be called
this.webService(request, ... // you passed the string '$.ws.userSignUpRequest' to this
if $.ws.userSignUpRequest is actually a reference to the webservice (as I suspect it is) then you should pass it directly (without quotes) to the constructor of GenericFormHandler
var handler = new GenericFormHandler('#template',$.ws.userSignUpRequest);
I am using indexedDB to store some offline data. In my code there is a loop inserting values to a store object:
function Insert(){
for(var i in list)
InsertList(list[i]);
alert("successful");
}
function InsertList(str){
var trans = LocalDB.indexedDB.db.transaction(StoreList, IDBTransaction.READ_WRITE);
var store = trans.objectStore(StoreList);
var data = {
"item": str};
var request = store.put(data);
request.onsuccess = function (e) { };
request.onerror = function (e) { alert("Error inserting"); };
}
The alert message will show before the loop executes, and if the page is refreshed or closed immediately after I close the alert message, some values are not inserted into the list because the loop was interrupted. So how can I know that the loop has ended and then give a successful message? Thanks.
The indexeddb API is async. This means you can only get feedback if something ended using a callback method in the success.
In your case I would work differently and insert everything in one transaction. When the transaction is completed, you get a callback. If that is called you can be sure everything is saved and the inserts are completed.
function Insert(){
var trans = LocalDB.indexedDB.db.transaction(StoreList, IDBTransaction.READ_WRITE);
var store = trans.objectStore(StoreList);
for(var i in list)
{
var data = { "item": list[i]};
var request = store.put(data);
request.onsuccess = function (e) { };
request.onerror = function (e) { alert("Error inserting"); };
}
trans.oncomplete = function ()
{
alert("successful");
}
}
I want to make a GET request using AngularJS and the GET contains email. This is the request:
var userResource = $resource('/GetUsers/?username=:username',{username:'#username'});
userResource.get({'username': 'test1#foot.com'}, function(user) {
console.log(user);
});
However, the callback function is never called. Please let me know what am I missing?
Looks good to me. Only thing i can imagine is that the callback function is not allowed to have a parameter. Angularjs Example:
var User = $resource('/user/:userId', {userId:'#id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});