I have following code:
App.Views.UseCategory = Backbone.View.extend({
template: HandlebarsTemplates['uses/useCategory'],
initialize: function() {
_.bindAll(this, 'render', 'addCategory');
this.render();
},
events: {
'submit #addCategoryForm': 'addCategory'
},
render: function() {
$(this.el).append(this.template(this.options));
return this;
},
addCategory: function(event) {
event.preventDefault();
var self = this;
var useCategoryId = $('select[id=use_category_id]').val();
this.model.set('category_id', parseInt(useCategoryId,10));
this.model.save({ success: console.log('success') });
}
});
Code above works and trigger success callback, so I receive in console "success".
But why when I change that addCategory function to:
addCategory: function(event) {
event.preventDefault();
var self = this;
var useCategoryId = $('select[id=use_category_id]').val();
this.model.set('category_id', parseInt(useCategoryId,10));
console.log('save?');
this.model.save({ success: this.addedCategory, error: function() { console.error(arguments) } });
},
addedCategory: function() {
console.log('success');
}
success callback is not triggered anymore, why?
Edit:
When you do:
this.model.save({ success: console.log('success') });
You already call your console log. What you should do is (not the same):
this.model.save({ success: function() {
console.log('success')
} });
Do you understand the difference or do you need clarifications?
In fact i suspect your success callback is never called.
EDIT:
model.save(data, opts) takes two arguments. You should do:
this.model.save({}, { success: function() {
console.log('success')
} });
Related
I need to run the success of ajax from a method function of object, this work when a pass to normal variable function
methodOne = function(data) {
alert(data);
};
$(document).on('click', ".clichere", function() {
var callback = function(){};
callback = methodOne;
runAjax({dispatch_ajax : "testing"}, callback );
});
function runAjax(data, succFunction) {
$.ajax({
type: "POST",
data: data,
success: succFunction,
error: function(error) {
alert(JSON.stringify(error));
},
});
}
this not work
var myapp = function() {
this.listTableOptions = function(data) {
alert(data);
};
};
$(document).on('click', ".clichere", function() {
obj = new myapp();
runAjax({dispatch_ajax : "testing"}, obj.listTableOptions() );
});
I can't not get the data in myapp object
You want to pass the function listTableOptions instead of executing it and passing the result so the following will work:
var myapp = function() {
this.listTableOptions = function(data) {
alert(data);
};
};
$(document).on('click', ".clichere", function() {
obj = new myapp();
runAjax({dispatch_ajax : "testing"}, obj.listTableOptions );
});
Notice obj.listTableOptions instead of obj.listTableOptions()
I have a model which is doing a fetch:
fetch: function (options) {
var self = this;
var def = $.Deferred();
P1Comm.get({
'dataType': 'json',
'processAjaxResponse': self.processAjaxResponse,
'onStatusInvalid': function (e) {
P1.log(e, 'status');
},
'onSuccess': function () {
options.success;
def.resolve();
},
'onError': function (e) {
P1.log(e);
def.reject();
},
'sourceURL': P1.API_APPS_ROOT + 'v1.0/accepted-terms'
});
return def.promise();
},
I have recently updated this to have the deferred functionality. However this has now broken my function in the view which sets the fetched data and puts it into the model.
fetchAcceptedTerms: function () {
var self = this;
this.appAcceptedTerms = new T1AppAcceptedTerms();
this.acceptedTerms = new AppAcceptedTerms();
this.acceptedTerms.fetch({
success: function (data) {
if (data.meta.status === 'success') {
self.appAcceptedTerms.set(data.data);
}
}
});
},
Before I changed the structure of the fetch to include deferred this function worked fine.
Can anyone point me in the direction of what I am doing wrong?
Thanks
UPDATE:
The fetch function when it was working (before the deferred) was this:
fetch: function (options) {
var self = this;
return P1Comm.get({
'dataType': 'json',
'processAjaxResponse': self.processAjaxResponse,
'onStatusInvalid': function (e) {
P1.log(e, 'status');
},
'onSuccess': options.success,
'onError': function (e) {
P1.log(e);
},
'sourceURL': P1.API_APPS_ROOT + 'v1.0/accepted-terms'
});
},
It's not clear why you need the extra Deferred here since get and fetch already return Promise objects, but as commenters have already indicated, you're not actually calling the options.success function:
'onSuccess': function () {
options.success;
def.resolve();
}
should be
'onSuccess': function(data) {
options.success(data);
def.resolve();
}
A button click triggers an ajax request. When the user clicks the button a second time while the first request is still loading, i want to override the first request's success function with another one.
Basically I want to do this:
var ajaxRequest = null;
jQuery('#mybutton').click(function () {
if (ajaxRequest) {
ajaxRequest.success = function () {
};
}
ajaxRequest = jQuery.ajax({
url: '...',
success: function () {
console.debug('do something');
}
});
});
But the initial success handler is been called.
How to achieve an override?
You can try the following hack, I have tested it with asynch setTimeout (instead of asynch jQuery.ajax) and it works -
var mySuccessHander = function() {
console.debug('Initial function');
}
var test = jQuery.ajax({
url: '...',
success: function() {
mySuccessHander();
}
});
And when the button is clicked for the second time, execute following -
mySuccessHander = function() {
console.debug('Overridden function');
}
Nice question , this will work..
var isRequestDone = true;
jQuery('#mybutton').click(function () {
var requestParams = {
url: '....',
beforeSend: function () {
isRequestDone = false;
},
success: function () {
isRequestDone = true;
console.debug('do something');
},
error: function () {
isRequestDone = true;
}
}
if (!isRequestDone) {
requestParams.success = function () {
console.log('please wait for a while!');
};
}
jQuery.ajax(requestParams);
});
beforeSend will fire just before the request will go to server , so when request in on the server isRequestDone will be false and hence will change success handler . on success callback from the first request it will again back to original.
You can set the ajax arguments to a variable first so you can modify it later on.
var clicks = 0,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}
};
$('#myButton').click(function() {
++clicks;
if (clicks > 1) {
// set the success function if clicked more than once
ajaxArgs.success = function () {
console.debug('Success function ' + clicks);
}
}
$.ajax(ajaxArgs);
});
If you want to modify the success function only when ajax is still loading you can do this:
var loading = false,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}, complete: function () {
loading = false;
}
};
$('#myButton').click(function() {
if (loading) {
// set the success function if ajax is still loading
ajaxArgs.success = function () {
console.debug('Another Success function ');
}
} else {
loading = true;
$.ajax(ajaxArgs);
}
});
Tried the following:
var collectionList = users.fetch();
alert(collectionList);
This returns null despite there being models in it.
Update - this worked for me:
users.fetch({
success: function() {
console.log(users.toJSON());
},
error: function() {
// something is wrong..
}
});
users.fetch({
success: function(response) {
_.each(response.models, function(model) {
//Do something with the model here
});
}
});
users.fetch().then(function () {
console.log(users.toJSON());
});
http://backbonejs.org/#Collection-fetch
Fetch is an async method, so is empty upon being called, after you specify success and error you should be able to then list your models.
users.fetch({
success: function() {
console.log(users.toJSON());
},
error: function() {
// something is wrong..
}
});
This one also can
var that = this;
users.fetch({
success: function(collection, response) {
console.log(that.collection.toJSON());
},
error: function() {
// something is wrong..
}
});
I have a dojo class like this.
var widget = declare("app.util",null, {
createSecuredLayers: function () {
$.ajax.get({
url: "/Api/GetLayer",
success: function (e) {
},
error: function () {
}
});
}
});
I want to use this object with callback parameters. I mean I want to pass success and error callbacks as parameter.
var util = new app.util();
util.createSecuredLayers({
success:function(){ },
error:function(){ }
});
createSecuredLayers: function(item) {
$.ajax.get({
url: "/Api/GetLayer",
success: item.successCallback,
error: item.errorCallback
});
}
When you call the method, don't forget to pass the response in the success callback.
util.createSecuredLayers({
successCallback: function(resp) {},
errorCallback: function(err) {}
});
You can do it like this:
var widget = declare("app.util",null, {
createSecuredLayers: function (args) {
$.ajax.get({
url: "/Api/GetLayer",
success: args.success,
error: args.error
});
}
});
var util = new app.util();
util.createSecuredLayers({
success:function(){ },
error:function(){ }
});
You should also consider using Dojo's deferred