2015-10-05 65 views
0

我有一個集合從中我想刪除一個模型,有它在實時同步到刪除骨幹收集模式:如何利用火力地堡

var ClientCollection = Backbone.Firebase.Collection.extend({ 
    model: Client, 
    url: "https://<my-firebase-url>.firebaseio.com", 
    autoSync: true 
}); 

我試圖從集合教職員以下使用我的clear功能:

var ClientView = Backbone.View.extend({ 
    tagName: "li", 
    className: "list-group-item", 
    template: _.template("<%= name %>"), 
    events: { 
    "click .destroy" : "clear" 
    }, 
    initialize: function() { 
    this.listenTo(this.model, "change", this.render); 
    }, 
    render: function() { 
    this.$el.html(this.template(this.model.toJSON())); 
    return this; 
    }, 
    clear: function() { 
     this.model.remove(); 
    }, 
}); 

但是,這隻能從DOM中刪除模型。

如何從服務器和DOM中刪除模型?

回答

0

集合視圖需要稍微改變,以便從DOM和服務器中刪除它。

使用listenTo確保更改同步將模型從DOM中刪除。

將以下內容添加到您的initialize函數中。

// This will listen for the destroy method and then remove the item from the dom 
this.listenTo(this.model, "destroy", this.remove); 

然後在clear功能使用destroy

clear: function() { 
    this.model.destroy({success: function(model, response) { 
     // Do something if successful 
    }}); 
}, 


完整視圖應該是這樣的:

var ClientView = Backbone.View.extend({ 
    tagName: "li", 
    className: "list-group-item", 
    template: _.template("<%= name %>"), 
    events: { 
    "click .destroy" : "clear" 
    }, 
    initialize: function() { 
    this.listenTo(this.model, "change", this.render); 
    this.listenTo(this.model, "destroy", this.remove); 
    }, 
    render: function() { 
    this.$el.html(this.template(this.model.toJSON())); 
    return this; 
    }, 
    clear: function() { 
    this.model.destroy({success: function(model, response) { 
     $('.notification').fadeIn(200).html('Success - Item removed').fadeOut(1000); 
     return this; 
    }}); 
    }, 
}); 


上面的代碼按預期工作