I have a relatively simple Backbone handled message container. I can add messages, and they display fine, but adding a delay to close them automatically does not work as undefined is passed on to the callback.
Could someone tell me how to properly specify the argument to be called? The main line is _.delay(function(){ messages.remove(this.model) }, 3000);
var Message = Backbone.Model.extend({
defaults: {
message: 'No message',
type: 'error'
},
/*validate: function( attrs ) {
if ( !attrs.type in ['error', 'warning', 'success', 'info'] ) {
return 'Wrong message type given';
}
}*/
});
var Messages = Backbone.Collection.extend({
model: Message
})
var messages = new Messages;
var MessageView = Backbone.View.extend({
template: Handlebars.compile( $('#t-message').html() ),
initialize: function() {
messages.bind('delete', this.remove, this);
},
render: function( event ) {
$(this.el).html( this.template( this.model.toJSON() ) );
// TODO: this never fires properly
_.delay(function(){ messages.remove(this.model) }, 3000);
return this;
}
});
var MessageContainerView = Backbone.View.extend({
id: 'messages',
initialize: function() {
messages.bind('add', this.addMessage, this);
},
render: function( event ) {
return this;
},
addMessage: function( message ) {
var view = new MessageView({model: message});
$('#' + this.id).append(view.render().el);
}
});
var messagecontainerview = new MessageContainerView;
messages.add(new Message({message: 'Close this in 3 secs.', type: 'success'}))
Of course this.model is defined inside the render method, but it’s undefined in the remove call.
It’s because
thisis bound to whatever is calling the delay callback function, not the view. Before you call_.delayassignvar self=this;Then useself.modelin the callback function.