BB: Mobile Nav collection
by kyllle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script type="text/x-handlebars-template" class="tmpl-card">
<div class="card {{#if isActive}}is-visible{{/if}}">
<h1>Order #{{id}}</h1>
<h2>Item: {{item}}</h2>
<p>{{isActive}}</p>
</div>
</script>
<script type="text/x-handlebars-template" class="tmpl-nav-item">
<button class="btn js-btn">Show {{item}}</button>
</script>
<button class="js-add-card">Add Card</button>
SCSS
* {
-webkit-font-smoothing: antialiased;
}
body {
padding: 5%;
}
.card {
background: white;
padding: 8px;
border: 1px solid #eee;
margin: 5px;
display: none;
&.is-visible {
display: block;
}
}
.nav {
margin-top: 10px;
}
JavaScript
console.clear();
var data = [
{
"id": 11478,
"item": "Item number 1"
}, {
"id": 12452,
"item": "Item number 2"
}, {
"id": 3125,
"item": "Item number 3"
}
];
var isMobile = true;
var CardModel = Backbone.Model.extend({
defaults: {
isActive: false
}
});
var CardsCollection = Backbone.Collection.extend({
model: CardModel,
initialize: function() {
this.listenTo(this, 'change:isActive', this.setActiveModel, this);
},
// http://stackoverflow.com/questions/28033487/set-an-active-property-to-only-1-model-in-a-backbone-collection-at-any-time
/**
* Makes sure the newly selected models isActive attribute has been set to true.
* Loops the collection setting true/false when comparing if the currently looped
* model doesn't equal the newly selected model and the models isActive value.
* If previously active has a true value then go ahead and set it to false.
*
* @param {object} selectedModel Backbone Model of the newly activated model in collection.
*/
setActiveModel: function(selectedModel) {
if(selectedModel.get('isActive') ) {
var previouslyActive = _.find(this.models, function(model) {
console.log(model != selectedModel && model.get('isActive'));
return model != selectedModel && model.get('isActive');
});
if (previouslyActive) {
previouslyActive.set('isActive', false);
}
}
}
});
var Cards = Backbone.View.extend({
className: 'orders',
isRendered: false,
initialize: function() {
this.fragment = document.createDocumentFragment();
this.listenTo(this.collection, 'add', this.addCard, this);
},
render: function() {
this.collection.forEach(this.addCard, this);
this.$el.html(this.fragment);
_.defer(function() {
...