5
votes

I've got a really great flow going across loading/rendering a collection, adding a new model to that collection, syncing that new model back to the database via an API, and then re-rendering my collection...but I'm running into one issue I can't get around:

Is there a standard "Backbone" way to insert a callback in a "create/sync to backend -> success" event, or should I just overwrite the create function? I could use the "add" method (that gets pinged whenever a new model is added to the collection/rendered on the dom), but then it would fire when each model is populated on page load...and I really only want it when the user creates/inserts a new model into the collection once the page is already rendered.

EDIT: If anyone else has this issue, back and forth with Elf below led me to the following solution:

Just add something along the lines of coll.trigger("newModelCreated", nextModel); to the success callback within Backbone.collection.create -- and then bind an event to that trigger within the view associated with that collection (so, in my view's initialize function I have this.collection.bind('newModelCreated', this.createAndAdd, this);.

Then, when that trigger is fired, I just route it to a special version of my "addOne" function (that I've dubbed createAndAdd) that renders my new model + the additional DOM stuff that I want associated with a freshly created one.

Not sure if the optimal solution, but it works for me.

2

2 Answers

2
votes

Who is responsible for assigning the unique key (the ID) for the object being created? The server or the client? My experience is that the server is the ultimate arbiter of IDs, as it has responsibility for storing them after the client has shut down.

My usual take is to have the model save itself, using the collection's URL as the target. The server should be smart enough to identify a POST to the collection as a "new object", and the server returns the saved object with the ID, which the new model then picks up. You can then add the model to the collection, and not have to do any overriding of the collection's add() method. (Obviously, when you add something to a collection, any listeners to the collection will get the collection.add event, which in turn should trigger renders of visible displays of that collection.)

0
votes

I had a similar problem while overriding backbone.sync to fetch data from mongodb. I called fetch in another part of my script, but needed to wait until the fetch was complete to do something with the data immediately afterwards. I just set up a Backbone event aggregator and triggered a fetchComplete event after the records were retrieved. Then in the other part of my script I bound the task using the fetched data (along with an unbind) to the fetchComplete event.