Backbone Collection, Marionette Views and CSS counters used to display field algebraic notation
With CSS counters, Marionette Views combined with Backbone Collection it becomes easy to generate algebraic notation characters, used to describe moves in chess. Is it final solution? It depends, it requires some weird CSS — but, if it won’t cause any problem with row identification it won’t be removed.
How it looks like
At this moment, like this:
How is it done
Vertical column of squares
First, we need to realize, that there is 10 rows instead of 8, because first and tenth will contain a-h characters:
_getRows: function () {
const rows = [];
for (let index = 0; index < 10; index++) {
rows.push({
index: (index + 1),
odd: !!((index + 1) % 2),
even: !((index + 1) % 2),
});
}
return new Backbone.Collection(rows);
},
Chessboard also needs to be aware about it:
childView: function (item) {
if (item.get("index") === 1 || item.get("index") === 10) {
return CharactersRowView;
}
if (item.get("odd")) {
return WhiteRowView;
}
if (item.get("even")) {
return BlackRowView;
}
},
And here’s CharactersRowView
:
const emptyElement = {character: ' '};
return Mn.CollectionView.extend({
template: _.template(`<div></div><br>`),
collection: new Backbone.Collection([
emptyElement,
{character: 'a'},
{character: 'b'},
{character: 'c'},
{character: 'd'},
{character: 'e'},
{character: 'f'},
{character: 'g'},
{character: 'h'},
emptyElement,
]),
childView: CharacterView,
tagName: 'section',
});
Fortunately, Backbone Collection can be initialized from simple array of objects, no need to create separated model for such simple thing — model will be created with character
property. How to display a character? When you provide a model to Marionette view
(in this case, CharacterView
), its properties are available to view
so it can be used in template (character-view.js
):
template: _.template(`<span><%= character %></span>`)
Horizontal row of squares
Here I decided to try CSS counters. Counters are created on body
:
body {
counter-reset: visible-row-number-left 9 visible-row-number-right 9;
}
And decremented on every span::before
element:
.field.field-number-left > span:before {
counter-increment: visible-row-number-left -1;
content: counter(visible-row-number-left);
}
.field.field-number-right > span:before {
counter-increment: visible-row-number-right -1;
content: counter(visible-row-number-right);
}
Unfortunately, it requires some weird CSS, because black/white fields are empty, and number field has content (number) they have to be manually positioned:
.field.field-number-left > span:before,
.field.field-number-right > span:before {
position: relative;
left: 18px;
top: 15px;
}
And also, it creates a gap between rows, so they have to be pulled up:
.field.field-black, .field.field-white {
margin-bottom: -35px;
}
Conclusion
Next post will be about detecting which field were clicked, and then I will made a decision if this way of displaying algebraic notation character is acceptable.