Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "fork" a model in Ember Data

I'm not sure if it's the correct way to express my requirement. But the word "fork" appears in the roadmap of Ember Data github page. And it's a killer feature in EPF. I'm wondering if I can do it in Ember Data.

The fork feature is useful when we have an edit page and bind a model. When we edit the information, I don't want the model properties to be changed because if the model properties are also displayed in other place they will be changed automatically. That's not what I want.

An example is a list on the left side of the page and a edit form for a specific model on the right side of the page. When I modify role name in the text field, the role name on the left side is changed because of data binding.

enter image description here

EPF solves this problem by "fork" the existing model and set it in a child session. The session in EPF is similar with store in Ember Data. When you modify the forked model it does not effect the model in the main session. After the forked model is updated it can be merged back to main session, and the corresponding model in main session are updated.

What I can think a solution in Ember Data is to create a different store and copy the model to that store. But it is a bit complicated. Does anyone have a better solution? I searched on stackoverflow and ember discuss forum and didn't find an answer.

like image 867
darkbaby123 Avatar asked Nov 23 '22 11:11

darkbaby123


1 Answers

I'm not sure if there is a standard or common way to do this in Ember, but I have written a Mixin that I can put on my routes to give some basic 'buffering' of the model:

App.BufferedRouteMixin = Ember.Mixin.create({
    setupController: function(controller, model) {
        this.setBufferFromModel(controller, model);
        this._super(controller, model);
    },
    setBufferFromModel: function(controller, model) {
        var buffer = {};
        controller.set('model', model);
        model.eachAttribute(function(name, meta) {
            buffer[name] = model.get(name);
        });

        controller.set('buffer', buffer);
    },
    setModelFromBuffer: function() {
        var model = this.get('model'),
            buffer = this.get('buffer');

        model.eachAttribute(function(name, meta) {
            if (buffer[name]) {
                model.set(name, buffer[name]);
            }
        });
    }
});

Once this is added to my Edit Route, I can call setModelFromBuffer in my save action. In my templates, I can use the {{#with buffer}} helper.

like image 153
Steve H. Avatar answered Dec 11 '22 03:12

Steve H.