JSFiddle - React, Tailwind, and code Playground

by octatone

HTML

<script src="https://raw.github.com/documentcloud/backbone/0.9.9/backbone.js"></script>
<!--

Expected behavior is that the change on attr2 is triggered on both collections 1 and 2, and that the change on attr1 is triggered on collecion 1 only.

-->

JavaScript

document.write('<h1>backbone 0.9.9</h1>');
// Create a model and give it some attributes
var model = new Backbone.Model;
model.set({
  
  'attr1': true,
  'attr2': true
});

var triggerCount = 0;

// Create two collections, one that is a 'main' collection, and the other a collection the 'main' collection will decide to also add the model to
// e.g. a sub collection
var collection1 = new Backbone.Collection;
var collection2 = new Backbone.Collection;

// Setup the main collection to listen for all changes on the model
collection1.on('change', function (model) {
  
  var changes = model.changedAttributes();
  _.each(changes, function (val, key) {
    
    document.write('trigger ' + ++triggerCount + '<br/>');
    document.write('collection1: ' + key + ' changed <br/>');
  });
});

// Setup the sub collection to listen for a particular attribute change
// and further trigger another change on the model on a different attribute
collection2.on('change:attr2', function (model) {
  
  document.write('trigger ' + ++triggerCount + '<br/>');
  document.write('collection2: attr2 changed <br/>');
  model.set({
    
    'attr1': false
  });
});

// Setup the bind on the main collection to add the model to the sub collection
collection1.on('add', function (model) {
  
  collection2.add(model);
});

// Add the model to the main collection
collection1.add(model);

// Trigger a change event on the model.
model.set({
  
  'attr2': false
});