asciidisco / Backbone.Mutators

Backbone plugin to override getters and setters with logic
http://asciidisco.github.com/Backbone.Mutators
228 stars 30 forks source link

(deleted) #1

Closed philfreo closed 12 years ago

philfreo commented 12 years ago

(nevermind -- sorry!)

asciidisco commented 12 years ago

Just beeing curious; does mutators work with relational? Never tried it, but would like to use relational in my next project...

philfreo commented 12 years ago

It does work -- only thing is you have to define a separate relational for the mutator if you want it to be serialized properly. Not too bad (just more verbose than it technically would have to be in some cases).

asciidisco commented 12 years ago

Could you provide a gist for this or smth. Would like to take a look on how the solution looks. May I can change smth. to make the integration smarter...

philfreo commented 12 years ago

Here's the basic idea. Originally I was having trouble (the last test was failing) because I didn't define the second relation.

test("can serialize a mutated model with nesting", function () {

    // Just making sure we can combine mutators with nested models 
    // and have the serialization work.

    var NestedModel = Backbone.RelationalModel.extend({
        defaults: {
            foo: 'bar'
        }
    });
    var Model = Backbone.RelationalModel.extend({
        defaults: {
            a: 'a',
            b: 'b',
            c: new NestedModel()
        },
        relations: [
            {
                type: Backbone.HasOne,
                key: 'c',
                relatedModel: NestedModel,
                includeInJSON: true
            },
            {
                type: Backbone.HasOne,
                key: 'state',
                relatedModel: NestedModel,
                includeInJSON: true
            }
        ],
        mutators: {
            state: function () {
                if (this.a === 'a') {
                    return this.c;
                } else {
                    return null;
                }
            }
        }

    });

    ok((new Model()).get('c') instanceof NestedModel, 'nested model is of proper type');
    equal((new Model()).toJSON().a, 'a', 'can serialize mutated model');
    deepEqual((new Model()).toJSON().c, (new NestedModel()).toJSON(), 'can serialize mutated model');   
    deepEqual((new Model()).toJSON().state, (new NestedModel()).toJSON(), 'can serialize mutated nested model');        
});
asciidisco commented 12 years ago

Thx. I will take a look on relational & how it deals with serialization.