【问题标题】:Backbone - Cannot get model on click using localstorage骨干 - 无法使用本地存储点击获取模型
【发布时间】:2014-12-11 17:54:28
【问题描述】:

我正在尝试在主干中设置一个小应用程序,我可以在其中将项目添加到列表中,当我单击它们时,它们将被删除。我已经设法将项目添加到列表中,但是使用 model.destroy() 时没有任何反应。

当我 console.log 我得到的列表模型上的点击事件时:

child {cid: "c0", attributes: Object, _sharing: false, _previousAttributes: Object, changed: Object…}

对于我点击的任何项目。

代码如下:

HTML:

<h1>INDEX!</h1>

<form class="add-form">
  <input type="text" name="name"/>
  <hr />
  <button type="submit" class="btn">Submit</button>
</form>

<h2>LIST STUFF</h2>

<ul class="blah">
{{#each indexCollection}}
  <li class="li-class">{{name}}</li>
{{/each}}
</ul>

Javascript:

//Local Storage
App.Storage.Local = new Backbone.LocalStorage('localIndexList1-backbone');


//Index Model
App.Models.IndexModel = Backbone.Model.extend({
  localStorage: App.Storage.Local,
  defualts:{
    name:''
  },
  urlRoot: '/'
});

//Index Collection
App.Collections.IndexCollection = Backbone.Collection.extend({
  localStorage: App.Storage.Local,
  model: App.Models.IndexModel,
  initialize: function(){
    console.log('Collection initialised');
  },
  url: '/'
});

//View for H1 and input form
App.Views.IndexView = Backbone.View.extend({
  el: '.page',
  events:{
    'submit .add-form' : 'addNew',
    'click' : 'deleteMe'
  },
  initialize: function(){
    console.log('IndexView initialised');
  },
  addNew: function(ev){
    // ev.preventDefault();
    var submitEntry = $(ev.currentTarget).serializeObject();
    var newEntry = new App.Models.IndexModel();
    newEntry.save(submitEntry, {
      success: function(newEntry){
        // router.navigate('', {trigger: true});
        console.log('SUCESSS!!!!!!!!!');
      }
    });
  },
  deleteMe: function(){
    console.log(this.model);
    //Whatever I put here will not work

  } 
});

//View for list
App.Views.ListView = Backbone.View.extend({
  el: '.page',
  initialize: function(){
    console.log('ListView initialised');
  },
  template: Handlebars.compile($('#list').html()),
  render: function(){
    this.$el.html(this.template);
    var that = this;
    var indexCollection = new App.Collections.IndexCollection();
    indexCollection.fetch({
      success:function(indexCollection){
        that.$el.html(that.template({indexCollection: indexCollection.toJSON()}));
      }
    });
  }
});

有人能帮忙告诉我哪里出错了吗?

谢谢!

【问题讨论】:

    标签: backbone.js local-storage


    【解决方案1】:

    您在哪里为您的每个集合模型创建一个IndexView?您应该有一个项目视图,将其模型配置为一个 IndexModel,并将删除代码移动到该特定视图。当你这样做时,你还应该在这个项目视图中调用remove

    这就是为什么像 Backbone.Marionette 这样的东西有很大帮助的原因。只需放入 CollectionView 即可。

    这样想:

    1. “列表视图”->有一个集合
    2. “项目视图” -> 有一个模型

    您需要在集合级别执行的任何操作(例如添加新的、重新加载等),在您的列表视图中执行。您在模型级别需要的任何内容(编辑、保存、删除),都可以在您的项目视图中完成。

    【讨论】:

    猜你喜欢
    • 2015-07-20
    • 2013-09-24
    • 2013-05-27
    • 2015-10-24
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2015-11-07
    • 2012-01-13
    相关资源
    最近更新 更多