Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove model in collection and fire remove event - backbone.js

how do I remove remove a model in collection and make the remove event fire . I tried people.remove([{ name: "joe3" }]); but it wont work.

var Person = Backbone.Model.extend({

    initialize: function () {
        console.log(" person is initialized");
    },
    defaults: {
        name: "underfined",
        age:"underfined"
    }
});

var People = Backbone.Collection.extend({
    initialize: function () {
        console.log("people collection is initialized");
        this.bind('add', this.onModelAdded, this);
        this.bind('remove', this.onModelRemoved, this);
    },
    model: Person,
    onModelAdded: function(model, collection, options) {
        console.log("options = ", options);
        alert("added");
    },
    onModelRemoved: function (model, collection, options) {
        console.log("options = ", options);
        alert("removed");
    },
});

//var person = new Person({ name: "joe1" });
var people = new People();



//people.add([{ name: "joe2" }]);
people.add([{ name: "joe1" }]);
people.add([{ name: "joe2" }]);
people.add([{ name: "joe3" }]);
people.add([{ name: "joe4" }]);
people.add([{ name: "joe5" }]);

people.remove([{ name: "joe3" }]);



console.log(people.toJSON());
like image 340
Hello-World Avatar asked Feb 25 '13 13:02

Hello-World


People also ask

How do I remove a model from a collection backbone?

write("<br>"); //The remove() method removes the 'player1' model from the collection. mycollection.

What is Backbone JS used for?

BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.

What is Backbone in programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

For anyone else looking for a remove where, you can simply chain it with a collection.where call. like so to remove all items matching the search:

people.remove(people.where({name: "joe3"}));

see Backbone collection.where

like image 119
Benjamin Kaiser Avatar answered Oct 18 '22 00:10

Benjamin Kaiser