關於部落格
- 一起墮落吧
  • 70735

    累積人氣

  • 9

    今日人氣

    0

    追蹤人氣

new article - knockout.js

介紹就不多寫了,可直接參閱黑暗執行緒的介紹:knockout.js!!

在遠古時代寫asp.net mvc beta的時候,一直苦無比較好的javascript template引擎,那時只好過著手工打造的生活,好家在當時已經有jquery了,不然可能連捶子都沒有。 練功用的的超簡易ToDoList(使用localStroage儲存)

<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/knockout-2.1.0.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.min.js"></script>
<script>
    var STORAGE_KEY = 'myToDoList',
        model = function (task) {
            var obs = ko.observable,
                cpu = ko.computed,
                self = this;
            task = task || {};
            $.each({
                isDone: obs(task.isDone || false),
                title: obs(task.title || null),
                dueDate: obs(task.dueDate || null),
                removeTask: function () {
                    if (confirm("確認刪除?")) {
                        if (taskList.indexOf(self) >= 0) {
                            taskList.remove(self);
                        }
                    }
                }
            }, function (n) {
                self[n] = this;
            });
        },
        taskList = ko.observableArray((function (s) {
            if (s.getItem(STORAGE_KEY) != null) {
                var _ = [];
                $.each(eval(s.getItem(STORAGE_KEY)), function () {
                    _.push(new model(this));
                });
                return _;
            }
        })(window.localStorage) || []);

    $(function () {
        if (taskList && taskList.length > 0) {
            ko.applyBindings({ taskList: taskList });
        }

        ko.applyBindings({ addTask: function () {
            var task = new model();
            taskList.push(task);
        }
        });

        $(window).unload(function () {
            window.localStorage[STORAGE_KEY] = ko.toJSON(taskList);
        });
    });
    
</script>
<div id="body">
    <div class="template" data-bind="foreach: taskList">
        <div>
            <input type="checkbox" data-bind="checked: isDone" />
            <input type="text" data-bind="value: title" />
            <input type="datetime" data-bind="value: dueDate, click: function(data, event){$(event.target).datepicker();return true;}"/>
            <button data-bind="click: removeTask">
                刪除</button>
        </div>
    </div>
    <button data-bind="click: addTask">
        +</button>
</div>
相關script檔案請自行調整對應路徑,datepicker效果要出來記得要載入jquery-ui的相關css檔案。
相簿設定
標籤設定
相簿狀態