Search code examples
javascriptjquerybackbone.jsbackbone.js-collections

Casting Backbone Collection object to its original type


I use backbone js to add custom elements to a backbone js Collection . I need to cast it back to its original type below is the

var Text = function () {

};

var Radio = function () {

};

function myfunction() {
    var collection = new Backbone.Collection();
    var t = new Text();
    var r = new Radio();
    collection.add(t);
    collection.add(r);

    alert(t instanceof Text);
    alert(collection.at(0) instanceof Text);

}

The statement alert(t instanceof Text); returns true where as the statement

alert(collection.at(0) instanceof Text); returns false .

Is there any way i could cast it to its original type ?


Solution

  • You can't.

    • collection.add(t) is equivalent to collection.add(new Backbone.Model(t)) when t does not inherit Backbone.Model1

    • Backbone.Model's constructor copies the attributes of t into the new object via Model.set but does not keep any other information on the source object2

    If you can, extend Backbone.Model to build Text and Radio

    var Text = Backbone.Model.extend({
    
    });
    

    If not, you will have to add additional information in your attributes to identify the correct prototypes.


    1 Annotated source code, Collection._prepareModel
    2 Annotated source code, Model.set