mardi 5 juillet 2016

extend/cast existing instance of model in backbone to be an instance of derived model (like casting in java)


I have a problem extending already existing instances of models to other type of derived model in backbone, is that possible?
if so, this is an example of what I need to do, please help:

var A = Backbone.Model.extend({
    initialize: function(options){
        console.log('A initialized');
    },
    foo : function{
        console.log('foo of A');
    }
});

var B= A.extend({
    initialize: function(options){
        A.prototype.initialize.apply(this, [options])
        console.log('B initialized');
    },
    foo : function{
        console.log('foo of B');
    },
    goo : function{
        console.log('goo of B');
    },
});

var ACollection = Backbone.Collection.extend({
    model: A
}

var BCollection = Backbone.Collection.extend({
    model: B
}

var aa = new ACollection();
var bb = new BCollection();

aa.create({
    attr1:1,
    attr2:2,
    attr3:3
}); // **A initialized**

// later after a while

var a = ACollection.at(0);
var b = cast a to type B    <---- how to do this

bb.add(b); // **A initialized**

// later after a while

console.log(bb.at(0).get(attr1)); // **1**
bb.goo(); // **goo of B**
bb.foo(); // **foo of B**

I don't want to clone the model 'a', because I may change attributes of 'a' elsewhere, and I want to see that also 'b' changed (the same object) thanks




Aucun commentaire:

Enregistrer un commentaire