Search code examples
javascriptnode.jsbackbone.js

How to extend new instance of module in NodeJS using Backbone


So im trying to extend 2 models in NodeJS using Backbone. My files are:

Form.js

var Backbone = require('backbone');

var Form = Backbone.Model.extend({
    _FormFields: [],
    AddField: function(Field) {
        this._FormFields.push(Field);
    }
});

module.exports = Form;

Register.js

var Form = require('../../../System/Libraries/Form');
var Input = require('../../../System/Libraries/Fields/Input');

var RegisterForm = Form.extend({
    Render: function() {
        this.AddField(new Input('Username'));
        this.AddField(new Input('Password'));
        this.AddField(new Input('PasswordConfirm', 'Password Confirm'));
    }
});

var fn = function() {
    var Module = new RegisterForm();

    return Module;
}

module.exports = fn;

And i want every time when i require it and call Render function to create new instance of Form too and extended it.

var Module = require('../../Application/Modules/Register/Register')();
if (Module.Render !== undefined && typeof(Module.Render) == 'function') {
        Module.Render();
}

When i require it now multiple times im recieving new instance of RegisterForm with (n x 3) fields in Form._FormFields.


Solution

  • You've got to get _FormFields off the prototype of Form. Pass an initialize() method to extend() when you create Form and assign this._FormFields = [] in it.