mikeric/rivets — pull request #186 by mikeric (2013-06-30 19:31:02+00:00)
Title: Components

This pull-request adds a simple, yet extremely flexible API for encapsulating reusable views. Components are declared as a custom element (prefixed with `rivets.config.prefix` or `rv`) and get compiled into their own `Rivets.View` instance on bind.

It's important to note that these elements will only exists in the template. They get replaced with a different DOM structure on bind, so you can think of it more as a set of instructions that get assembled into something more complex. Their purpose is purely for encapsulation and to clean up your templates, not as a way to mock "web components" or "custom elements" — those are different concepts that Rivets.js shouldn't care about, but should play well with in the future. You'll be able to write regular binders for them just as you would with any other elements, but that's a whole other topic.

Here's what they look like in your templates.

```html

```

They are also good way to add partial loading in your app.

```html

```

Components are defined as an object with two properties. `attributes` and `build`.

```javascript
rivets.components.partial = {
attributes: ["ref"],

build: function() {
return App.templates[this.ref]
}
}
```

- `attributes` is an array of attributes that you want to use internally while building the component view.
- `build` is a function that returns the DOM template for the component view. Attributes defined on the `attributes` array will be available on `this` within the `build` function.

Any additional attributes set on the element that are not defined in the `attributes` array will get used for scope inflection. For example, let's say you are binding to `user.name` within the component's template, but you don't necessarily want `user` to be `user` from the parent view, you instead want `user` to be `session.speaker` from the parent view. All you need to do is add `user="session.speaker"` on the element and it will use that when binding the component view.