Geert-Jan
Geert-Jan

Reputation: 18895

rivets.js: prepopulate model with data from view on init

Perhaps this seems a bit backwards, but I have a view bound with Rivets.js for which I'd like the view to populate the model on initialization.

The usecase is that I'm using server-side rendering to return a snippet (the view) including rivets' data-attributes. So NO JSON is returned from server to client.

Now, by pressing 'edit' a user may put the content in 'edit'-mode, and start editing at will. (Using contenteditable, but this is out of scope here I guess).

So how to make sure the model is populated with values from the view on init?

Upvotes: 1

Views: 756

Answers (3)

Bifz
Bifz

Reputation: 403

This question is old but it still has no accepted answer, so here goes:

You need to disable the preload configuration so rivets doesn't override whatever is in the input with what you have in your model at the time you do the binding. This can be done via the preloadData=false configuration, either globally (rivets.configure(...)) or view-scoped (third param to rivets.bind(...)).

After the binding, you need to publish the view (pull the values to your model). You also need to set up the observers via sync() call, otherwise your binded methods won't be triggered.

Using the same example as the previous answers:

var view = rivets.bind($('#auction'), { auction: auction }, {
  preloadData: false
});

view.publish();
view.sync();

Upvotes: 0

Xander
Xander

Reputation: 1244

I know that this question is a little outdated but I recentry tried rivets and I came across the same problem.

The solution:

// In your rivets configuration you disable preload:
rivets.configure({
  templateDelimiters: ['[[', ']]'],
  preloadData: false
});

// you bind your data
var binding = rivets.bind($('#auction'), {auction: auction});

// you manually publish it once to populate your model with form's data
binding.publish();

And that's it. I still don't know how to disable prelaod per bind

Upvotes: 1

Geert-Jan
Geert-Jan

Reputation: 18895

From the example on Rivets website (assign to 'rivetBinding')

var view = rivets.bind($('#auction'), {auction: auction});

doing rivetBinding.publish(); will bootstrap the model with values from the view for all bindings that have 'publishes = true'.

Upvotes: 0

Related Questions