389 views(since 2013/10/08)

Knockout.js でTodoアプリ (Visual Studio2013)

概要

Todoアプリのハンズオンを行うための資料です。

knockout-todo


/Views/Home/ index.cshtml

@{
    ViewBag.Title = "Knockout_Todos";
}

<h2>knockout - Todo</h2>
<div class="container">
    <div class="col-lg-12">
        <div class="input-group">
            <input type="text" class="form-control" data-bind="value: title"/>
            <span class="input-group-btn">
                <button class="btn btn-info" data-bind="click: addTask">Add</button>
            </span>
        </div>
    </div>

    <div class="col-lg-12"><h3>Task List</h3></div>

    <div class="col-lg-12">
        <ul class="list-group" data-bind="foreach: tasks">
            <li class="list-group-item">
                <span data-bind="text: title"></span>
                <a href="#" data-bind="click: $parent.deleteTask" class="pull-right">
                    delete
                </a>
            </li>
        </ul>
    </div>
</div>

@section scripts{
    <script type="text/javascript" src="~/Scripts/knockout-3.1.0.js"></script>
    <script type="text/javascript" src="~/Scripts/test.js"></script>
}

/Scripts/ test.js

$(function () {
    function Task(title) {
        this.title = title;
    }

    function ViewModel() {
        var self = this;
        self.title = ko.observable("");

        self.tasks = ko.observableArray([]); //配列の変更を検知する
        self.addTask = function () {
            var task = new Task(self.title());
            self.tasks.push(task);
            self.title("");
        };

        self.deleteTask = function (task) {
            self.tasks.remove(task);
        }
    }
    ko.applyBindings(new ViewModel());
});

参考

Filed Under: .NETJavaScript

About the Author

野呂清二(ご連絡はこちらまで (http://www.exceedone.co.jp/inquiry/)

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.