Skip to content

Instantly share code, notes, and snippets.

// global event dispatcher
Backbone.View.prototype.eventAggregator = _.extend({}, Backbone.Events);
// create two different views
var view1 = new Backbone.View();
var view2 = new Backbone.View();
// and attach a listener on view1
view1.eventAggregator.on(‘disconnect’, function() {
console.log('view1 disconnected');
var ItemView = Backbone.View.extend({
method: function() {
this.log('method() called');
}
});
var items = [
new ItemView(),
new ItemView(),
new ItemView()
Backbone.Model.prototype.log =
Backbone.View.prototype.log = function() {
console.log.apply(console,
['[' + this.cid + ']'].concat([].splice.call(arguments, 0))
);
};
Backbone.View.extend({
remove: function() {
this.closeModal();
this._super('remove', arguments);
}
});
Backbone.Model.prototype._super =
Backbone.View.prototype._super =
Backbone.Router.prototype._super =
Backbone.Collection.prototype._super = function(funcName){
return this.constructor.__super__[funcName].apply(this, _.rest(arguments));
};
Backbone.View.extend({
remove: function() {
this.closeModal();
this.constructor.__super__.remove.apply(this, arguments);
}
});
var model = new Backbone.Model();
model.debugEvents();
model.trigger('change', 'foo', 'bar'); // event “change” with ['foo', 'bar']
Backbone.Collection.prototype.debugEvents =
Backbone.Model.prototype.debugEvents =
Backbone.View.prototype.debugEvents =
Backbone.Router.prototype.debugEvents = function() {
this.on('all', function(eventName) {
console.log('event “' + eventName + '” with ', Array.prototype.slice.call(arguments, 1));
});
}
Backbone.View.extend({
render: function() {
this.template(tmplStr, {}); // will call the template engine we chose
}
});
// underscorejs version
Backbone.View.prototype.template = function(tmpl, params) {
return _.template(tmpl, params);
};
// handlebars version
Backbone.View.prototype.template = function(tmpl, params) {
return tmpl(params);
};