Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any Backbone.js tutorials that teach ".sync" with the server?

I read many Backbone.js tutorials, but most of them deal with static objects.

Of course, I have data on the server. I want a tutorial that shows how backbone.js can communicate with the server to fetch data, post data, etc.

This is .sync, right? I read the backbone.js documentation, but still fuzzy on how to use this feature.

Or can someone show me an example?

According to: http://documentcloud.github.com/backbone/#Sync

Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server.

But when? Where do I put the function? I don't know how to use it, and the documentation doesn't give any examples. When does the data get loaded into my models? I get to define when...right?

like image 313
TIMEX Avatar asked Nov 28 '11 04:11

TIMEX


2 Answers

You never really have to look at .sync, unless you plan to overwrite it. For normal uses, you can simply call model.save() whenever you want and that will execute a post or put (depending on whether the record exists already). If you want to get the data from your backend, use collection.fetch()

You'll of course also need to specify a URL, do so through your collection attribute, collection.url

like image 93
Krishna Avatar answered Sep 19 '22 16:09

Krishna


You can override Backbones native sync functionality if you override it:

Backbone.sync = function() {
  //Your custom impl here
}

After that this function is called whenever you call a backbone function like .save() on models or .fetch() on collections. You do not have to care about data transport anymore.

I would suggest taking a look into Backbones source and look how the default sync function is implemented. Then create your own or adopt your server to support the native function.

like image 40
ProTom Avatar answered Sep 16 '22 16:09

ProTom