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.