Pergunta

I'm trying to create a "base class" for a controller in Backbone.Marionette. I guess this question could be answered by someone with knowledge about backbone aswell since Marionette extend in the same as backbone. What I have done is to first create a Marionette.Controller that will work as a base controller by extending from Marionette.Controller. I have then extended the base controller further to add more specialized functionallity. I'm calling the base controllers initilize function from the child by using the prototype. This seemed to be working fine until I noticed that the base seems to be static. In the example below, the childid will be unique for each instance. The baseid however will be the same for all instances, the latest added baseid.

App.Common.BaseWidget.Controller = Marionette.Controller.extend({
    initialize: function (options) {
        this.model = options.model;
        this.id = options.baseid;
        this.region = options.region;
    }
});

App.Widgets.ChildWidget.Controller = App.Common.BaseWidget.Controller.extend({
    initialize: function (options) {
        App.Common.BaseWidget.Controller.prototype.initialize(options);
        this.id = options.childid;
    }
});
var widgets = []
widgets.push( new App.Widgets.ChildWidget.Controller({ "model": model , "region": region, "baseid": App.newGuid(), childid: App.newGuid() }));

Does anyone know what's causing this?

Foi útil?

Solução

You probably need to set the proper scope for initialize:

App.Widgets.ChildWidget.Controller = App.Common.BaseWidget.Controller.extend({
    initialize: function (options) {
        App.Common.BaseWidget.Controller.prototype.initialize.apply(this, arguments);
        this.id = options.childid;
    }
});

Outras dicas

In backbone You can call parent's methods using __super__ of constructor:

App.Widgets.ChildWidget.Controller = App.Common.BaseWidget.Controller.extend({
    initialize: function (options) {
        this.constructor.__super__.initialize.apply(this, arguments);
        this.id = options.childid;
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top