I am using Backbonejs and Backgrid and would like to set up an event listener inside the Backgrid view to catch events triggered in another view. The event would call a function to clear the currently checked tickbox. I am using the basic event aggregator concept from Derick Bailey's excellent article on passing events between views.
I am stuck at two points:
1) Successfully passing the event into the Backgrid view.
2) Determining which tickbox is checked in order to clear it.
My Backgrid column code is as follows:
window.ShowCollectionView = Backbone.View.extend({
template: _.template($('#CollectionTemplate3').html()),
initialize: function(options) {
var isTickBoxSelected = false;
// Tie the method uncheckTickBox() to the view and not the aggregator.
_.bindAll(this, "uncheckTickBox");
options.vent.bind("uncheckTickBox", this.uncheckTickBox);
var columns = [
{
name: '',
label: 'Select',
cell: Backgrid.BooleanCell.extend({
events : {
'change': function(ev){
var $checkbox = $(ev.target);
var $checkboxes = $('.backgrid input[type=checkbox]');
if($checkbox.is(':checked')) {
$checkboxes.attr("disabled", true);
isTickBoxSelected = true;
// Disable all checkboxes but this one
$checkbox.removeAttr("disabled");
console.log("Box now checked");
} else {
// Enable all checkboxes again
$checkboxes.removeAttr("disabled");
isTickBoxSelected = false;
console.log("Box now UNchecked");
}
}
}
})
}, {
name: "id", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable
cell: "string"
}, {
name: "last_name",
label: "Surname",
editable: false, // Display only!
cell: "string" // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up
}];
<more code here>
// Set up a grid view to use the pageable collection
var userGrid = new Backgrid.Grid({
vent: vent,
columns: columns,
collection: userCollection
});
I was able to solve this by creating a method such as follows:
uncheckTickBox: function(){
var $allcheckboxes = $('.backgrid input[type=checkbox]');
var $tickedcheckbox = $('.backgrid input[type=checkbox]:checked');
// Uncheck ticked box
$tickedcheckbox.prop("checked", false);
// Enable all checkboxes again
$allcheckboxes.removeAttr("disabled");
}
It isn't perfect as the event lives in the view hosting the grid (parent view) and not in the grid itself. However, it works well and the trigger and listener are still nicely decoupled thanks to the event aggregator.
I may try to improve it by caching the checkbox selector when the grid is created and using it to reset all the checkboxes.