Mihtril Todo

by dirkk0

HTML

<script src="//cdn.jsdelivr.net/mithril/0.1.11/mithril.min.js"></script>

<h2>Index</h2>

<div id="mithrilContent"></div>

JavaScript

var todo = {};

//for simplicity, we use this module to namespace the model classes

//the Todo class has two properties
todo.Todo = function (data) {
    this.description = m.prop(data.description);
    if (data.done !== undefined) {
        this.done = m.prop(data.done);
    } else {
        this.done = m.prop(false);
    }
};

//the TodoList class is a list of Todo's
todo.TodoList = Array;

//the controller uses 3 model-level entities, of which one is a custom defined class:
//`Todo` is the central class in this application
//`list` is merely a generic array, with standard array methods
//`description` is a temporary storage box that holds a string
//
//the `add` method simply adds a new todo to the list
todo.controller = function () {
    var self = this;
    this.list = new todo.TodoList();
    this.description = m.prop("");

    this.add = function () {
        if (self.description()) {
            self.list.push(new todo.Todo({
                description: self.description()
            }));
            self.description("");
        }
    };

    this.changeInput = function () {
        self.description("Changed"); //test 2 way binding
    };

    this.fireOnEnter = function (e) {
        self.description(e.target.value);
        e.preventDefault();
        if (e.keyCode == 13) self.add()
        //callback.apply(undefined, arguments);
    };
};

//here's the view
todo.view = function (ctrl) {
    return m("div", [
    m("input", {
        onkeyup: ctrl.fireOnEnter,
        value: ctrl.description()
    }),
    m("button", {
        onclick: ctrl.add
    }, "Add"),
    m("button", {
        onclick: ctrl.changeInput
    }, "Change"),
    m("table", [
    ctrl.list.map(function (task, index) {
        if (!task.done()) {
            return m("tr", [
            m("td", [
            m("input[type=checkbox]", {
                onclick: m.withAttr("checked", task.done),
                checked: task.done()
            })]),
            m("td", {
             ...