Diving into Data Binding

I assume you're wondering "What is all this fuse about? Nothing really new so far". Well, from here we begin with data-binding - something that Backbone definitely lacks of. In ngBackbone we can bind multiple models and collections to a component. We just pass a map of named models/collections with @Component or with view options and the data get available immediately in the template.

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

@Component({
  el: "ng-hello",
  models: {
    hero: new Model({ name: "Superman" })
  },
  template: `<p><b data-ng-text="hero.name"></b> says:</p>
  <h1>Hello World!</h1>
  `
})

class HelloView extends View {
}

let hello = new HelloView();
hello.render();

You may wonder what is that <b data-ng-text="hero.name">. That is a directive of ngTemplate DOM-based template language. You can find details in Mastering ngTemplate chapter.

In the previous example we bound a model. Let's do it now with a collection:

As you can guess when the bound data change we have the template updated. In the example below we bind DOM event (click on the button) the classical Backbone way by using events map. In the handler onButtonClick we retrieve the model of interest from the map this.models.get( "state" ) and increment its counter property.

Template reflects also data changes caused by storage events. If we fetch a collection the template synchronizes as soon as the data updates:

Last updated

Was this helpful?