Cormant-Incorporated / backbone-nested-types

Backbone Model mixin that provides toJSON(), parse(), and validate() implementations for models with nested types.
MIT License
5 stars 1 forks source link

Anonymous nesting is not supported #7

Closed russplaysguitar closed 7 years ago

russplaysguitar commented 7 years ago

If you try to use an additional model mixin with this mixin which also overrides toJSON and calls this.constructor.__super__.toJSON.apply(this, arguments);, an infinite loop occurs due to the nested type mixin calling toJSON with the child context.

A rough way to fix this in the nested types mixin would be something like:

toJSON: function (options) {
            var superJSON = this.constructor.__super__.toJSON;
            var originalConstructor = this.constructor;
            this.constructor = this.constructor.__super__.constructor;
            var json = superJSON.apply(this, arguments);
            this.constructor = originalConstructor;

           ...
russplaysguitar commented 7 years ago

Example failing test:

        it('should serialize model using multiple mixins with toJSON calls', function () {
            var OtherMixin = {
                toJSON: function() {
                    return this.constructor.__super__.toJSON.apply(this, arguments);
                }
            };

            var MultipleMixinModel = Backbone.Model.extend({
                toJSON: function() {
                    return { foo: 'bar' };
                }
            }).extend(OtherMixin).extend(NestedTypeMixin);

            var multipleMixinModel = new MultipleMixinModel();

            // act
            var actual = multipleMixinModel.toJSON();

            expect(actual).to.eql({ foo: 'bar' });
        });