JSFiddle - React, Tailwind, and code Playground

by madobon

HTML

<form>
    <ul id="icecreams">
        <!-- ここにビューがアイスクリーム一覧を構築する -->
    </ul>
</form>
<div id="icecream-list">
    <!-- ここにビューが現在の選択内容を書き込む -->
</div>

JavaScript

/*
 * WEB+DBPRESS vol.53
 * MVC 実践編
 * 交通整理された設計を実現しよう
 */

// モデル: アイスクリーム一覧
var icecreamModel = {
    list: [{
        id: 't1',
        name: "バニラ"
    }, {
        id: 't2',
        name: "チョコレートチップ"
    }, {
        id: 't3',
        name: "オレンジシャーベット"
    }, {
        id: 't4',
        name: "チョコミント"
    }, {
        id: 't5',
        name: "ストロベリー"
    }, {
        id: 't6',
        name: "抹茶"
    }],
    // すべてのアイスクリームを返す(getter)
    getAll: function () {
        return this.list;
    },
    // IDで指定したアイスクリームオブジェクトを返す
    findById: function (id) {
        return $.grep(this.list, function (val) {
            return id === val.id;
        })[0];
    }
};

// モデル: 選択されているアイスクリームの管理
var selectionModel = {
    // 選択されているアイスクリームが入る
    list: [],
    // アイスクリームの個数
    icecreamNumber: 2,
    // アイスクリームを追加する
    add: function (item) {
        var list = this.list;
        list.push(item);
        if (list.length > this.icecreamNumber) {
            // アイスクリーム制限個数以上の場合は
            list.shift(); // 0番めを捨てる
        }
        this.updateView(); // ビューを更新
    },
    // 指定したアイスクリームが選択されていればtrueが返る
    contain: function (icecream) {
        return this.list.indexOf(icecream) >= 0;
    },
    // IDで指定したアイスクリームが選択されていればtrueが返る
    containById: function (id) {
        return this.contain(icecreamModel.findById(id));
    },
    // 選択されているアイスクリームを返す(getter)
    getIcecreams: function () {
        return this.list;
    },
    // ビューを更新する
    updateView: function () {
        // ビューを更新するコード 

        updateSelection();
        updateIcecreamList();
    }
};

$(function () {
    var $els = $('#icecreams');
    $.each(icecreamModel.getAll(), function (i, icecream) {
        $els.append(
        $('<li />')
            .append($('<input type="checkbox" />').attr('name', icecream.id))
            .append($('<span />').text(icecream.name))
            .click(function (event) {
            onclickIcecream(event);
        }));
    });
    selectionModel.updateView();
});

// ビュー:...