Sharing Data Across Components

Often that happens that we refer to the same data from different components. We need those components to update whenever that data change. That is easy to achieve with ngBackbone. We can instantiate a model or collection and pass the reference to all the corresponding components. For instance we can take the example from Nesting Components and change our foo.ts and bar.ts to build a list of worlds from collections named worlds:

foo.ts

import { Component, View } from "ng-backbone";

@Component({
  el: "ng-foo",
  template: `Hello, it's Foo
  <dl><dt data-ng-for="let world of worlds" data-ng-text="world.name"></dt></dl>`
})

export class FooView extends View {
  initialize(){
    this.render();
  }
}

The collection itself we create in app.ts and pass it to AppView and both FooView and BarView with view options:

app.ts

import { Component, View, Collection, Model } from "ng-backbone";
import { FooView } from "./foo";
import { BarView } from "./bar";

let worlds = new Collection([
  new Model({ name: "Post-Crisis Earth" }),
  new Model({ name: "Red Son" }),
  new Model({ name: "The Fourth World" }),
  new Model({ name: "The Dakotaverse" })
]);

@Component({
  el: "ng-hello",
  events: {
    "click button" : "addNewWorld"
  },
  views: {
    foo: [ FooView, { collections: { worlds: worlds } } ],
    bar: [ BarView, { collections: { worlds: worlds } } ]
  },
  template: `
  <button>Add a new world</button>
  <table width="60%">
  <tr>
  <td><ng-foo></ng-foo></td>
  <td><ng-bar></ng-bar></td>
  </tr>
  </table>`
})

class AppView extends View {
  addNewWorld(){
    let worlds = this.collections.get( "worlds" );
    worlds.add(new Model({
      "name": "A brand new world"
    }));
  }
}

let app = new AppView({ collections: { worlds: worlds }});
app.render();

As we press the button, both the lists update:

Last updated