0

I have a backbone collection of models.

MyCollection = Backbone.Collection.extend({
   model: myMymodel;
});

MyModel = Backbone.Model.extend({
...
});

Each model has a view

myView = Backbone.View.extend({
  initialize: function() {
    this.model = new MyModel();
  };
});

There is no persistence on the server-side. This is just for structuring client-side information. So the models do not have ids, and a url for Backbone.sync has not been configured.

From within the view, I want to remove the model from the collection.

I have tried the following:

this.model.trigger( "destroy" );

However it does not work. The destroy event is not propagating to the collection.

Any idea what I'm doing wrong?

Thanks,

4

2 回答 2

2

我认为您根本没有实例化集合。至少不能从代码中看出这一点。如果您只是创建一个模型实例但没有将其添加到任何集合中,this.model.trigger("destroy");则不会执行任何操作。

myView = Backbone.View.extend({
  initialize: function() {
    this.coll = new MyCollection();
    this.model = new MyModel();
    this.coll.add(this.model);
  };
});

现在模型是集合的一部分:

this.model.destroy()

进行删除 api 调用并从集合中删除

this.collection.remove(this.model)

从集合中删除模型,但不进行删除 api 调用。

this.model.trigger("destroy");

在模型上触发破坏事件,但不会破坏模型本身。就collection.remove(this.model)好像模型是集合的一部分一样。

于 2013-03-07T10:26:18.503 回答
0

collection.remove(model)将是一个更合适的功能,因为您没有将模型保存在服务器端。Backbone.Collection.remove

于 2013-03-06T18:56:20.360 回答