Geert-Jan
Geert-Jan

Reputation: 18905

View-to-Model formatters in Rivets.js

Loving Rivets.js for it's power yet simplicity. However, how to define formatters that take a view-property and format it to a model-property? To my understanding Formatters are meant to operate the other way around, i.e.: from Model to view.

Are View to Model formatters supported somehow, or does this have to be hacked?

Upvotes: 2

Views: 1480

Answers (1)

Michael Richards
Michael Richards

Reputation: 1811

This is a feature that was brought in to Rivets.js 0.4.2. Big thanks to GMFlash and mdekmetzian on GitHub for implementing it.

Basically you just define bidirectional formatters as an object instead of a single function. When a formatter is defined as a single function, Rivets assumes it to be in the read direction only. When a formatter is defined as an object, Rivets uses it's read and publish functions to effectively serialize and de-serialize a value.

rivets.formatters.date = {
  read: function(value) {
    return value.format("DD/MM/YYYY")
  },
  publish: function(value) {
    return moment(value, "DD/MM/YYYY")
  }
}

You can also chain bidirectional formatters with any other formatters, and in any order. They read from left to right, and publish from right to left (skipping any read-only formatters when publishing the value back to the model).

Apologies for the lacking documentation. The homepage doesn't reflect at all the current feature set of Rivets.js and needs to be updated to include added features such as this.

Upvotes: 6

Related Questions