treecoder
treecoder

Reputation: 45101

backbone: how to pass bootstrap data without server side tags

The normal way to bootstrap your app with backbone as described in the docs is this

var Accounts = new Backbone.Collection;
Accounts.reset(<%= @accounts.to_json %>);

Here, we are using the server side tags <%= ... %>, <?php echo ... ?>, etc.

But in my app I am passing very thin HTML from the server. Something like this

<html><head></head><body></body>
<script src="init.js"></script>
<html>

In this case how should I bootstrap my data for my backbone models and collections?

Backbone recommends against using fetch

Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place. fetch is intended for lazily-loading models for interfaces that are not needed immediately.

But I wonder if that's the right thing to do in cases like mine?

Upvotes: 1

Views: 1084

Answers (2)

lecstor
lecstor

Reputation: 5707

I didn't want to put my opinion as an answer, but I think I can say, "there is no reason, technical or otherwise, not to use fetch to load your models on page load in this use case". 8)

Upvotes: 3

fguillen
fguillen

Reputation: 38792

You need your JS code to be parsed by your server side platform and that it inserts the data on it.

Two approaches can be:

1. Make you init.js to be parsed by your server side

<html>
  <script src="init.js.php"></script>
<html>

In your initi.js.php you can use the interpolate tags.

2. Load the data in a separate interpretable JS file

<html>
  <script src="data.js.php"></script>
  <script src="init.js"></script>
<html>

The data.js.php can be some thing like this:

MyApp.data = <?php echo ... ?>

In your init.js you can use MyApp.data to reset your Collections.

Upvotes: 1

Related Questions