2014-10-16 33 views
0

我正在嘗試在骨幹中設置一個小應用程序,我可以將項目添加到列表中,當我點擊它們時,它們將被刪除。我設法將項目添加到列表中,但是在使用model.destroy()時沒有任何反應。骨幹 - 無法使用本地存儲獲取模型點擊

當我CONSOLE.LOG在列表模式我得到的單擊事件:

孩子{CID: 「C0」,屬性:對象,_changing:假的,_previousAttributes:對象,改變了:對象...}

我點擊的任何項目。

代碼如下:

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()})); 
     } 
    }); 
    } 
}); 

會有人能夠幫助讓我知道我錯了?

謝謝!

回答

0

你在哪裏爲每個收藏模型創建一個IndexView?您應該有一個項目視圖,將其模型配置爲一個IndexModel,並將您的刪除代碼移動到該特定視圖。當你這樣做時,你也應該在這個項目視圖中調用remove

這就是爲什麼像Backbone.Marionette這樣的東西有很多幫助。只需投入一個CollectionView即可完成。

把它看成是這樣的:

  1. 「列表視圖」 - >具有收藏
  2. 「項目視圖」 - >有一個單一的模式

任何你需要在集合級別(如添加一個新的,重新加載,不管),在你的列表視圖中執行。在模型級別上需要的任何東西(編輯,保存,刪除),在您的項目視圖中執行。

+0

感謝您的回答,爲我闡明瞭一些事情。所以列表視圖應該呈現列表中的所有項目視圖? – Blahh 2014-10-16 13:14:35

+0

準確。通常情況下,您會構建一個專用類型的視圖CollectionView,它基本上爲該集合中的每個項目呈現另一個視圖。看看https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.collectionview.md – CharlieBrown 2014-10-16 13:54:15

+0

非常感謝您的幫助! – Blahh 2014-10-16 14:01:55