Reputation: 1830
I want updatePlays function to be called as a callback function when an AJAX call is successful. I thought that using underscore bind would let me refer 'this' as the Collection object that I actually want to update, but I'm having trouble here. When I get to the function that should update collection, it thinks that 'this' refers to 'window'.
In this situation, a Backbone Model has Backbone Collection, which are made from another backbone models.
in view:
SomeView: Backbone.View.extend({
someFunction: function(e) {
var field = this
this.picker = new PlayPicker({
field:field,
model: new PlaySet({
plays: new Collections.Plays({}),
slot: field.model
})
})
}
})
PlayPicker:Backbone.View.extend({
...
refresh: function () {
this.model.update()
},
....
Collection that's part of model PlaySet
Plays:Backbone.Collection.extend({
model: Play ,
initialize: function () {
plays = this
_.bind(this.updatePlays, plays) // Where I thought I should bind
},
updatePlays: function (plays) {
new_plays = []
var i;
for (i = 0; i < plays.length; i++){
new_plays.push(new Play({
id: plays[i]["id"],
text: plays[i]["text"]
}));
}
this.reset(new_plays) // Uncaught TypeError: Object [object Window] has no method 'reset'
}
})
Model PlaySet
PlaySet: Backbone.Model.extend({
update: function() {
this.get('slot').fetchAssociatedPlays(this.get('plays').updatePlays)
},
})
Model Slot - does the AJAX call
Slot:Backbone.Model.extend({
...
fetchAssociatedPlays: function(update) {
thisModel = this
$.ajax({
url: thisModel.associatedPlaysURL(),
success: function (collection) {
update(collection)
}
})
}})
Should this be achievable with underscore bind, and where/how would be the correct way?
Thank you in advance.
Upvotes: 0
Views: 509
Reputation: 1830
The answer to this question has helped me fix my issue: Binding a callback in Backbone.js and Underscore.js
callBack = _.bind(callBack, this);
It was that I need to use a function that is the result of binding the first function with some object.
Upvotes: 0