将数据添加到本地存储Backbone.js时重新渲染

时间:2017-04-27 21:16:57

标签: backbone.js

我希望在将数据添加到localstorage时重新呈现我的UserList, 因为我正在为两个标签写聊天,而在一个标签中我添加用户我想要另一个标签也在列表中显示它们。 UpdateUser可用于从localstorage获取数据到用户列表,然后当用户列表更改时,它调用函数AddAll(),但它不起作用:(

<script type="text/javascript">
'use strict';
var app = {}; 


app.User = Backbone.Model.extend({
  defaults: {
    name: '',
    status: ''
  }

});

app.UserList = Backbone.Collection.extend({
  model: app.User,
  localStorage: new Store("people"),

});

app.userList = new app.UserList();

app.UserView = Backbone.View.extend({
  tagName: 'li',

  template: _.template($('#item-template').html()),
  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    return this; 
  },
  initialize: function(){
    this.model.on('change', this.render, this);
    this.model.on('destroy', this.remove, this); 
  },

});
 app.AppView = Marionette.View.extend({
  el: '#chatapp',
  initialize: function () {
    app.userList.on('add', this.addAll, this);
    app.userList.on('reset', this.addAll, this);
    app.userList.on('change', this.addAll, this);
    this.updateMessages();
    this.createUser();
  },
  updateMessages:function(){
      setInterval(function(){
      app.userList.fetch();
      }, 1000);

  },
  createUser: function(){

    app.userList.create(this.newAttributes());
  },
  addOne: function(user){
    var view = new app.UserView({model: user});
    $('#user-list').append(view.render().el);
  },
  addAll: function(){
    this.$('#user-list').html(''); 
    app.userList.each(this.addOne, this);

  },
  newAttributes: function(){
    return {
      name: prompt('What is your name?', 'name'),
      status: prompt('What is your status?', 'status')
    }
  }
});
app.appView = new app.AppView(); 

</script>

1 个答案:

答案 0 :(得分:1)

您还没有说过您提供基于localStorage的同步的“商店”所使用的内容,因此很难提供准确的代码示例。但是,如果您将这些额外的行添加到@initialize方法:

var model = this;

$(window).bind('storage', function (e) {
    model.fetch(); 
});

每当localStorage发生更改时,这将导致模型从localStorage重新加载。您可以通过检查e.originalEvent.key来改进这一点,并仅对该模型的localStorage中的更改做出反应。除了更新localStorage对象并导致事件的事件之外,每个窗口/选项卡都会触发一个存储事件,并且只有在对localStorage进行更改时才会触发,因此您不必担心在模型中抑制对localStorage的更改自救。