jesseskinner / hover

A very lightweight data store with action reducers and state change listeners.
MIT License
98 stars 7 forks source link

State as another class with finder & copy method on it? #15

Closed sipte closed 9 years ago

sipte commented 9 years ago

Would it hurt to have a function like following, where State is a separate class and have helper functions on it. is this good practice.

var SimpleStore = function(path) {
    function State() {
        this.data = [];
        this.selected = null;
    }

    var p = State.prototype;

    p.copy = function() {
        var ns = new State();
        ns.data = this.data;
        ns.selected = this.selected;

        return ns;
    }

    p.findById: function(id) {
        return _.find(this.data, function(item) {
            return item.id === id;
        });
    }

    var store = Hoverboard({
        init: function(state) {
            GET(path, function(data) {
                store.data(data);
            });

            return new State();
        },

        data: function(state, data) {
            var ns = state.copy();
            ns.data = data;

            return ns;
        },

        select: function(state, selected) {
            var ns = state.copy();
            ns.selected = selected;

            return ns;

        }
    });

    return store;
}
jesseskinner commented 9 years ago

@0419 I hadn't thought of that technique, but you can definitely do that.

Note that you can also put functions in your state, and if you used a plain object for your state, Hoverboard automatically copies into a new object each time.

So something like this would be basically the same, but a bit simpler:

var SimpleStore = function(path) {
    function findById(id) {
        return _.find(this.data, function(item) {
            return item.id === id;
        });
    }

    var store = Hoverboard({
        init: function(state) {
            GET(path, function(data) {
                store.data(data);
            });

            return { data: [], selected: null, findById: findById };
        },

        data: function(state, data) {
            return { data: data };
        },

        select: function(state, selected) {
            return { selected: selected };
        }
    });

    return store;
}
jesseskinner commented 9 years ago

@0419 I just realised that Hoverboard was treating class instances as plain objects, ie. it would copy the properties over when you use a class instance as your state. I only intended that true plain objects (those created with {} or new Object) would do this. I'll fix this bug - so your original example will work better and you won't lose your instance.