JSFiddle - React, Tailwind, and code Playground

by wookiehangover

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/master/backbone.js"></script>
<p>Initial State:</p>
<pre class="ex0"></pre>

<p>Activating 'bar':</p>
<pre class="ex1"></pre>

<p>Activating 'foo':</p>
<pre class="ex2"></pre>

CSS

pre { padding-bottom: 2em; }

JavaScript

var Model = Backbone.Model.extend({
    defaults: {
        state: 0                        
    }
});

var Collection = Backbone.Collection.extend({
    model: Model,
    
    initialize: function(){
        this.on('change:state', function(model, state){
            if(state === 1){
                _.each(this.without(model), function(m){
                    m.set({ state: 0 }, { silent: true });
                });
            }                            
        }, this);        
    },
    
    activate: function(name){
        var active = this.where({ name: name });
        if(active[0]){
            return active[0].set({ state: 1 }); 
        }           
    }
});

var collection = new Collection([
    { name: 'foo' },
    { name: 'bar' },
    { name: 'biz' }
]);

$('.ex0').html(JSON.stringify(collection.toJSON(), '', '  '));

collection.activate('bar');
$('.ex1').html(JSON.stringify(collection.toJSON(), '', '  '));

collection.activate('foo');
$('.ex2').html(JSON.stringify(collection.toJSON(), '', '  '));