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.
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:
import { Component, View, Model, Collection } from "ng-backbone";
@Component({
el: "ng-hello",
collections: {
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" })
])
},
template: `<h1 data-ng-for="let world of worlds">
Hello <i data-ng-text="world.name"></i>!
</h1>
`
})
class HelloView extends View {
}
let hello = new HelloView();
hello.render();
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.
import { Component, View, Model } from"ng-backbone";@Component({ el:"ng-hello", events: {"click button":"onButtonClick" }, models: { state:newModel({ counter:0 }) }, template:`<button>Discover a new world!</button> <span>Discovered worlds: <mark data-ng-text="state.counter"></mark></span> `})classHelloViewextendsView {// Handle click on the buttononButtonClick(){let state =this.models.get( "state" );state.set( "counter",state.get( "counter" ) +1 ); }}let hello =newHelloView();hello.render();