如何在Backbone集合中跟踪实际呈现的模型

时间:2016-08-03 10:21:01

标签: javascript backbone.js

我是Backbone的新手,我正在尝试创建一个简单的幻灯片,显示集合中的所有模型。

通过从服务器获取来创建模型,这里是代码:

var Post = Backbone.Model.extend({
  defaults:{
    text: "",
    source: "",
    image: "",
    posted_at: "",
    rendered : false,
  },
});

在PostCollection中,modelBefore和modelAfter分别返回next和previous模型。

var PostCollection = Backbone.Collection.extend({
  model: Post,
  url: "https://milkytags.com/api/v1/boards/edcb2c43-1448-4c81-97d5-1c315c8f9589/posts",

  initialize: function() {
    this.fetch({ data: $.param({ page: pageCounter, per_page:3}) });
  },

  parse: function(response) {
    return response.posts;
  },

  modelBefore: function(model) {
    index = this.indexOf(model) - 1;
    if (index < 0) {
      index = this.length - 1;
    }
    return this.at(index);
  },

  modelAfter: function(model) {
    index = this.indexOf(model) + 1;
    if (index === this.length) {
      index = 0;
    }
    return this.at(index);
  },
});

我创建了一个名为SlideShowView的视图,该视图从依赖Post View的模板创建视图:next和prev方法处理渲染下一个或上一个模板。

var SlideShowView = Backbone.View.extend({
  tagName: 'div',
  className: 'slideshow',
  events: {
    'click #close': 'close',
    'click #next': 'next',
    'click #prev': 'prev',
  },
  template: _.template($('#slideShowTemplate').html()),

  initialize: function() {
    this.render();
  },

  render: function() {
    this.$el.html(this.template());
    post = new PostView({ model: this.model });
    this.$el.append(post.el);
    return this.$el;
  },

  close: function(){
    this.remove();
  },

  next: function(){
    var next =  this.model.collection.modelAfter( this.model );
    post = new PostView({ model: next });
    this.$el.html(this.template());
    this.$el.append(post.el);
    return this.$el;
  },

  prev: function(){
    var prev= this.model.collection.modelBefore( this.model );
    post = new PostView({ model: prev });
    this.$el.html(this.template());
    this.$el.append(post.el);
    return this.$el;
  },
});

最后,发布视图:

// The View for single Post
var PostView = Backbone.View.extend({
  tagName: 'div',
  className: 'post',
  events: {
    'click' : 'slideShow',
  },
  template: _.template($('#postTemplate').html()),

  initialize: function() {
    this.render();
  },

  render: function() {
    this.$el.html(this.template(this.model.toJSON_milky()));
    return this;
  },

  slideShow: function(){
    test=new SlideShowView({model: this.model});
    $('#milkyContainer').append(test.$el);
  }
});

当我按下next或prev时出现问题,实际上就好像集合没有使用最新的渲染元素更新,我必须找到一种方法来告诉集合显示的当前集合元素是什么。

提示?

由于

1 个答案:

答案 0 :(得分:0)

目前您的代码在this.model中使用SlideShowView作为“当前模型”。但是,您不会更新它。像这样的东西会这样做:

next: function(){
    var next =  this.model.collection.modelAfter( this.model );
    post = new PostView({ model: next });
    this.$el.html(this.template());
    this.$el.append(post.el);
    this.model = next; // <<---- Added this line.
    return this.$el;
},

同样适用于prev