如何使用Backbone Marionette CompositeView显示嵌套的模型集合?

时间:2014-04-15 20:43:21

标签: javascript backbone.js marionette

我正在关注两个教程,以便在我的Backbone应用程序(http://lostechies.com/derickbailey/2012/04/05/composite-views-tree-structures-tables-and-more/http://davidsulc.com/blog/2013/02/03/tutorial-nested-views-using-backbone-marionettes-compositeview/)中使用嵌套的CompositeViews,但是我在修改两个模型相关的情况时遇到了麻烦通过将一个模型的id存储在另一个模型中。

我试图通过每个电影列出下面相关演员的电影列表。

这是我目前所拥有的显示电影列表但不呈现任何演员名单的内容:

MovieApp.module("ActorsApp.List", function(List, MovieApp, Backbone, Marionette, $, _){
  List.Controller = {
    listActors: function(){
      var actors = MovieApp.request("actor:entities");
      var movies = new Backbone.Collection;
      var allMovies= MovieApp.request("movie:entities");

      actors.each(function(actor) {
        movieId = actor.get("movieId");

        if (!movies.get(movieId) ){
          console.log("Movie not found. Adding to list list.");
          movie = allMovies.get(movieId);
          selectedActors = actors.where({ movieId: movieId });
          console.log("Selected Actors: ", selectedActors);
          movie.actors=selectedActors;
          movies.add(allMovies.get(movieId));

        }
        else {
          console.log("Movie found in list. Skipping.")

        }
      });

      var moviesListView = new List.Movies({
        collection: movies
      });

      MovieApp.mainRegion.show(moviesListView);
    }
  }
});



  /* list_view.js */


PassCake.module("SitesApp.List", function(List, PassCake, Backbone, Marionette, $, _){
  List.Actor = Marionette.ItemView.extend({
    tagName: "li",
    template: "#actor-list-item",

    initialize: function(){
      console.log("Actor ItemView: " + this.model.get('title'));

    }

  });

  List.Movie = Marionette.CompositeView.extend({
    tagName: "li",
    template: "#actor-movie-list-item",
    itemView: List.Actor,
    initialize: function(){

       console.log("Actors: ", this.model.actors);

        actors = this.model.actors;

        /* The following line throws an error saying TypeError: obj[implementation] is not a function obj[implementation](name, callback, this);
           Outputting this.model.actors seems to work but it isn't working when assigned to this.collection. 
        */
        this.collection = actors;

        console.log("Movie view initialized");
    }



  });

  List.Movies = Marionette.CompositeView.extend({
    tagName: "div",
    template: "#actor-movies-list",
    itemView: List.Movie,
    itemViewContainer: "#actors-movies"
  });

});

我对Backbone很陌生,所以我也很想知道如何让这个更干净。谢谢你看看!

1 个答案:

答案 0 :(得分:7)

首先,再使用var,你宣布了很多全局变量。

我的猜测是行this.collection = actors;,actor不是Backbone Collection它可能是一个数组,假设actors.where({ movieId: movieId });返回一个数组。

尝试将行更改为this.collection = new Backbone.Collection(actors)