CRUD local database with Kendo

by JayData

HTML

<script src="http://cdn.kendostatic.com/2012.3.1315/js/kendo.all.min.js"></script>
<script src="http://include.jaydata.org/datajs-1.0.3.js"></script>
<script src="http://include.jaydata.org/jaydata.js"></script>
<script src="http://include.jaydata.org/jaydatamodules/kendo.js"></script>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2012.3.1315/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2012.3.1315/styles/kendo.default.min.css">
<h3>Define a model, invoke basic store operations</h3>
<p>This example calls <b>$data.define("Task")</b> to create a model named Task, then invokes <i>Task</i>.readAll(), <i>Task</i>.addMany() and 
    <i>Task</i>.query() to work with task data</p>

<h3><pre>Task.readAll()</pre></h3>
<ul id="items"></ul>
<h3><pre>Task.query('it.Completed == true')</pre></h3>
<ul id="completed"></ul>

CSS

body{
    font-family: Segoe UI Light
}

JavaScript

$(function () {
    var Task = $data.define("Task", {
        Todo: String,
        Completed: Boolean
    });
    

    Task.readAll() //readAll returns a promise, use 'then' to resolve
        .then(function(tasks) {
            //if there is no data, add some
            if (tasks.length == 0) {
                //addMany returns a promise not an actual array
                //in the next 'then' we receive this as array
                //this is necessary since all operations are async
                return Task.addMany([
                    { Todo: 'Include script files', Completed: true },
                    { Todo: 'Define model' },
                    { Todo: 'Connect data to grid' }
                ]);        
            }
            return tasks;
        }).then(function(tasks) {
            //this gets executed after new items are created if db was empty
            renderTasks(tasks, '#items');
            Task.query("it.Completed == true")
                .then(function(completedTasks) { renderTasks(completedTasks, '#completed'); });
        });

    function renderTasks(tasks, container) {
        tasks.forEach(function(task) {
            $(container).append('<li>' + task.Todo + '</li>');
        });
        return tasks;
    }

});