简体   繁体   中英

Backbone embedded collection event

I've created a model (see Delegation) made of basic attributes (name, activity) and one collection (members).

See jsfiddle

The fetch method update the model and trigger a sync event on it - but I would like to be notified when the embedded collection is synced (ie in a real case to render a view when the inner collection is synced).

I tried this

this.listenTo(this.get('members'),'sync',function(){...}

but the corresponding event never fires.

What is the proper way to have it triggered?

When you execute the fetch function of Backbone , it returns a PROMISE , you can use the function then to launch a function at the moment the fetch is finished, you can also use the catch for when it fails.

For example:

this.model = new Backbone.Model()
this.model.url ="example"
this.model.fetch().then((data) => { 
    console.log("succes: " + data); // Finished the fetch successfully 
  }).catch((data) =>{ 
    console.log("error: " + data); // The fetch ended in error
  })

For your code:

You can use it in this part Backbone.Model.prototype.fetch or if your fetch function returns a Promise, use it when calling the fetch of the model.

I don't see any code that fetches the collection, hence sync is not triggered on the collection. You should do delegation1.get('members').fetch() . For this to work, the collection should have it's own URL as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM