I have the following situation:
var Task = Backbone.Model.extend({
initialize: function() {
},
save: function() {
$.ajax({
type : "POST",
url : "/api/savetask",
data : this.toJSON(),
success : function (response) {
this.trigger("something", "payload");
}
});
}
});
When I run this, I get the following error
this.trigger
is not a function
On the external approach, I can trigger stuff.. like
var task = new Task();
task.trigger("something","payload");
What I am doing wrong? or not doing :)
I have the following situation:
var Task = Backbone.Model.extend({
initialize: function() {
},
save: function() {
$.ajax({
type : "POST",
url : "/api/savetask",
data : this.toJSON(),
success : function (response) {
this.trigger("something", "payload");
}
});
}
});
When I run this, I get the following error
this.trigger
is not a function
On the external approach, I can trigger stuff.. like
var task = new Task();
task.trigger("something","payload");
What I am doing wrong? or not doing :)
Share Improve this question edited Jul 3, 2014 at 12:49 edi9999 20.6k15 gold badges98 silver badges135 bronze badges asked Apr 5, 2012 at 14:02 DigitalWMDigitalWM 4,5163 gold badges20 silver badges15 bronze badges3 Answers
Reset to default 12this
in the anonymous function refers to the ajax object. This is because "this" in javascript changes with respect to the scope of the function. In order to reference "this" of the initial function, assign it to a different variable. The following will work:
save: function() {
var self = this;
$.ajax({
type : "POST",
url : "/api/savetask",
data : this.toJSON(),
success : function (response) {
self.trigger("something", "payload");
}
});
}
EDIT: See an explanation of how "this" is determined.
Personally I prefer having a saveSuccess
method on the model.
save: function() {
var self = this;
$.ajax({
type : "POST",
url : "/api/savetask",
data : this.toJSON(),
success : this.saveSuccess
});
},
saveSuccess: function(response) {
this.trigger("something", "payload");
}
This is a very late answer, but in case anyone else happens upon this page: there is a much better way. Using the self object (in my experience) is considered a bit of an anti-pattern, since we use underscore.js and have access to the bind
function. Anyway, here's a better way:
var Task = Backbone.Model.extend({
initialize: function() {
},
save: function() {
$.ajax("/api/savetask", {
type : "POST",
data : this.toJSON(),
context : this,
success : function (response) {
this.trigger("something", "payload");
}
});
}
});
It may be the case that the context
attribute was added in a recent version of jQuery, and it wasn't available before. But this is (in my opinion) the best way to do it.