0

Here's what I'm attempting to do: I first load a list of active site users, and each of these users is associated with a list of movies. When I click on a user, I want his list of movies to appear on the next menu over. But instead of loading the full movie list for each user on the initial JSON request, I'm attempting to do some lazy loading using the model.fetchRelated("key") option that is packaged with backbone-relational.

In my view, I have an event listener:

events: {
    'click .username': 'showMovies'
},
showMovies: function(event){
    event.preventDefault();
    this.model.select();
}

and in my model I have a select function:

select: function(){
    this.set({selected: true});
    this.fetchRelated("movies");
    var usermovies = new UserMovieCollection(); 
    usermovies.add(this.get("movies"));     
}

The problem is that this.fetchRelated("movies") is an asynchronous event, so when 'add' is called, the movies aren't actually loaded. So I'm wondering what my options are here. One idea I had was to somehow wrap this into jQuery's deferred objects... basically, use a callback. I'm not exactly sure how to do this, though, and I'm not sure if using a form of callbacks is really good Backbone design.

Does anyone know how I could implement this, either using callbacks or some (preferable) system? Thanks!

EDIT:

I have managed to get it using deferred, but I'm still wondering if there is a better backbone solution without deferred.

select: function(){
        var model = this; 
        var usermovies = new UserMovieCollection();
        $.when(this.fetchRelated("movies")).then(function(){
            console.log(model.get("movies"));
        });
    }
bento
  • 4,846
  • 8
  • 41
  • 59

1 Answers1

1

In looking through the docs a bit, it looks like there may be an event you can bind to?

var user = new User({ name: 'User 1' } );
user.bind( 'add:movies', function( model, coll ) {
    // Maybe this will work?
});

I am not TOO familiary with Backbone.Relational, so this may or may not work...

Good luck either way!

jcreamer898
  • 8,109
  • 5
  • 41
  • 56
  • Thanks for the response. I thought that something like this might work, but unfortunately it doesn't seem to really do the job. For now I've been using $.when and .then from jquery, and then pulling an collection.each(function(model){}); to render them. It seems like a poor solution, to be honest. – bento May 25 '12 at 04:35