Backbone从集合中移除不起作用

时间:2014-04-19 15:53:33

标签: backbone.js

var Wine = Backbone.Model.extend({
    winename: "Charles Shaw"
})

var Wines = Backbone.Collection.extend({
    Model: Wine
})

var divElement = Backbone.View.extend({
    initialize: function () {
        this.render();
    },
    tagName: "ul",
    render: function () {
        $("#div1").empty();
        $("#div1").append("<ul id='ulList'></ul>"),
        wines.each(function (model) {
            $("#ulList").append("<li>" + model.winename + "</li>");
        });
        return this;
    }
});

var wine1 = new Wine();
wine1.winename = "wine1";
var wines = new Wines();
wines.add(wine1);

var wine2 = new Wine();
wine2.winename = "wine2";
wines.add(wine2);

function changewinename(model, winename) {
    this.winename = winename;
}

var d = new divElement(wines);
wines.on("add", addwinename);
wines.on("remove", removewinename);
function addwinename(model, winename) {
    d.initialize();
}

function removewinename(model, winename) {
    d.initialize();
}

function AddWine() {
    var winename = $("#wineName").val();
    var wineFromUI = new Wine();
    wineFromUI.winename = winename;
    wines.add(wineFromUI);
    $("#wineName").val("");
}

function changewinename(model, winename) {
    this.winename = winename;
}

function RemoveWine() {
    var wineValue = $("#wineName").val();
    var wine1 = new Wine();
    wine1.on({ "change:winename": changewinename });
    wine1.set({ winename: wineValue });        
    alert(wine1.winename);
    wines.remove(wine1);
    $("#wineName").val("");
}

模型的集合删除无效。添加工作正常。

1 个答案:

答案 0 :(得分:0)

你需要在你的集合中添加一个函数,如下所示:

var Wines = Backbone.Collection.extend({
    Model: Wine,
     removeElement: function(elements, options) {
        return this.remove(elements, options);
     }
})

并在您的视图中将其命名为:

wines.removeElement(wine1);