2015-11-24 40 views
0

我有以下代碼:更新一集動態查看從中取出款後

// Create the Backbone view to display a list of vehicles 

var Vehicle = Backbone.Model.extend({ 
    idAttribute: "registrationNumber", 
    urlRoot: "/api/vehicles", 
    validate: function(attrs) { 
    if (!attrs.registrationNumber) 
     return "Registration number is required!"; 
    } 
}); 

var Vehicles = Backbone.Collection.extend({ 
    model: Vehicle 
}); 

// View for the model 
var VehicleView = Backbone.View.extend({ 
    tagname: "li", 
    attributes: { 
    "data-color" : "Rainbow" 
    }, 
    events: { 
    "click .deleteButton" : "deleteVehicle" 
    }, 

    render: function() { 
    var template = _.template($("#vehicleTemplate").html()); 
    var html = template(this.model.toJSON()); 
    this.$el.html(html); 
    return this; 
    }, 

    deleteVehicle: function() { 
    console.log("Model destroyed"); 
    this.model.destroy(); 
    } 
}); 

var VehiclesView = Backbone.View.extend({ 
    tagName : "ul", 

    initialize: function() { 
    this.model.on("change", this.render, this); 
    this.model.on("add", this.render, this); 
    this.model.on("remove", this.render, this); 
    }, 

render: function() { 
    var self = this; 

    this.model.each(function(vehicle){ 
     var vehicleView = new VehicleView({model: vehicle}); 
     self.$el.append(vehicleView.render().$el); 
    }); 
} 

}); 

// Add cars to the collection 
var car1 = new Vehicle({registrationNumber: "XLI887", color: "blue"}); 
var car2 = new Vehicle({registrationNumber: "ZNP123", color: "blue"}); 
var car3 = new Vehicle({registrationNumber: "XUV456", color: "grey"}); 

var vehicles = new Vehicles([car1, car2, car3]); 

var vehiclesView = new VehiclesView({el: "#container", model: vehicles}); 
vehiclesView.render(); 

渲染看起來不錯,但是當我點擊刪除,新的集合(少了一個元素)追加到舊集合的現有視圖。我如何用新的取代舊的集合視圖?

回答

0

我修改了下面的「remove」處理程序,它動態地從列表中刪除了「li」元素並顯示了新的集合。

initialize: function() { 
    this.model.on("change", this.render, this); 
    this.model.on("add", this.render, this); 
    this.model.on("remove", this.onDelete, this); 
}, 

onDelete : function(vehicle) { 
    console.log("Vehicle deleted"); 
    this.$el.find("li#" + vehicle.id).remove(); 
}