2

A common pattern I come across is a backbone collection which is initially seeded from a database.

However, the user can also add to the collection. When the user does add to the collection, these should be reflected in the db.

Usually I would bind some kind of server call to the collection add event. However if I do that, the call will be made even during the initial seed. I only want it to be called on new data.

Whats the right way to tackle this problem?

  • Can you bind to a local function, which checks the value of an isDataLoading variable/property/method-call before making the server-side call? – jimbobmcgee Jun 17 '14 at 16:42
  • @jimbobmcgee I could, but how do I update that variable? How do I tell when the collection has completed loading the seed data? Also, there's the possibility of a user quickly adding to the collection before the seed data is fully loaded. – Aakil Fernandes Jun 17 '14 at 17:07
  • How is the data getting from your database to your collection? You must be loading it in somehow. Set it before and after that. – jimbobmcgee Jun 17 '14 at 18:04
  • As for preventing users from modifying data before you're ready, have the isDataLoading variable control visibility and/or enabled state of your controls / have the state-changing controls check the isDataLoading variable in their event handlers, before updating state / create the controls dynamically only after you've seeded the collection. – jimbobmcgee Jun 17 '14 at 18:07
1

How do I tell when the collection has completed loading the seed data?

Define an initialize function:

var foo = new Backbone.Model({
  "Name": "foo"
});

var bar = new Backbone.Collection(null, {
  model: foo,
  initialize: baz
  }
});

Also, there's the possibility of a user quickly adding to the collection before the seed data is fully loaded:

Use a separate model for the user-generated content:

function callback(event)
  {
  callback.model = new Backbone.Model({"Name":event.target.value});
  }

Then use set to merge them when initialize is called:

function baz()
  {
  try
    {
    foo.set({"Name": callback.model.get("Name")});
    }
  catch(e)
    {
    console.log(e);
    }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.