0

I have an array, that I need to populate with multiple 'properties', something like this:

[
    {
        name: 'Date',
        value: '27 Oct'
    },
    {
        name: 'Type',
        value: 'Image'
    },
    {
        name: 'Client',
        value: 'Apple'
    }
]

I want to list out all the properties in ul and I want to have a + button, that will add a new object to an array (initially name and value will be blank). After double clicking on each item (li in this case), I want to make these properties editable.

So I did something like this:

var Properties = {};

Properties.items = [
    {
        name: m.prop('Date'),
        value: m.prop('21 Dec'),
        editable: m.prop(false)
    }
];

This is my initial array.

Then, I have a controller:

Properties.controller = function() {
    this.addNewItem = function() {
        Properties.items.push({
            name: m.prop('Sample'),
            value: m.prop('Test'),
            editable: m.prop(false)
        })
    };

    this.toggleEditable = function(item) {
        item.editable(!item.editable());
        console.log(item.editable());
    };
};

My view:

Properties.view = function(ctrl) {
    return m('ul.list-unstyled', [
        Properties.items.map(function(item) {
            return m('li', [
                item.editable() ? m('input', {
                    value: item.name(),
                    onkeyup: function(e) {
                        if(e.keyCode == 13) {
                            ctrl.toggleEditable.bind(ctrl, item);
                        } else {
                            m.withAttr('value', item.name)
                        }
                    }
                }) :
                m('span', {
                    ondblclick: ctrl.toggleEditable.bind(ctrl, item)
                }, item.name()),
                m('span', ': '),
                m('span', item.value())
            ]);
        }),
        m('div',{
            onclick: ctrl.addNewItem.bind(ctrl)
        }, '+')
    ]);
};

And finally:

m.mount(document.querySelector('.container'), Properties);

But when I start typing, it sort of overwrites what I wrote and doesn't save the new value..

Any ideas, anyone?

Such Much Code
  • 787
  • 1
  • 9
  • 26

1 Answers1

2

You should keep your original array as the data model, pass it to Properties and let Properties store only the editable state. That is a nice data separation and will simplify the code. It may fix the save problem as well, since it can just set the array value directly in the onkeyup event.

For the overwrite problem, maybe adding a key attribute will work? It seems related. Check out http://mithril.js.org/mithril.html#dealing-with-focus for more information.

ciscoheat
  • 3,719
  • 1
  • 35
  • 52