block by enjalot 630d636f1ae0db4e517c

derby-standalone example. inserting derby templates into an otherwise native html page.

Full Screen

index.js

var app = derby.createApp();
// convenience function for loading templates that are defined as <script type="text/template">
app.registerViews();

//allow us to easily explore derby from the console
window.APP = app;
window.MODEL = app.model

app.component('posts', Posts);
function Posts() {}
Posts.prototype.init = function(model) {
  // init is called at the time of instanciation
  model.setNull('selectedIndex', 0);
};
Posts.prototype.select = function(post,i) {
  // we've defined a view function, i.e. a function that can be called from the view
  console.log("selected:", i, post)
  this.model.set('selectedIndex', i);
};

var page = app.createPage();

// lets drive things by some data. this is of course 
page.model.set('_page.posts', [
  { title: "hello world", text: "hey hi how are you doing?"},
  { title: "where am i?", text: "oh thats right i'm here"},
  { title: "so reuseful", text: "derby!"},
]);

// page.getFragment gets the template we gave the id="body" to.
console.log("fragment", page.getFragment('body'))
// we append our main template into the #content div of our otherwise non-derby site
document.getElementById('content').appendChild(page.getFragment('body'))
// the main example uses the following code because it presumes the entire body should be rendered by derby
// document.body.appendChild(page.getFragment('body'));

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <!-- you probably have your CSS in some other files -->
  <style>
  .header {
    background: #84bfff;
  }
  .content {

  }
  .footer {

  }
  .post {
    padding: 15px;
    border: 1px solid gray;
  }
  </style>
</head>

  <body>
    <div class="header">
      This is my homepage
    </div>

    <div id="content">
    <script type="text/template" id="body">
      <posts list="{{_page.posts}}"></posts>
    </script>
    </div>

    <div class="footer">
      End homepage.
    </div>

    </body>

    <script type="text/template" id="posts" data-element="posts">
      <div class="posts">
        {{each list as #post, #i}}
          <div class="post" on-click="select(#post, #i)">
            <h3>{{#post.title}}</h3>
            <p>{{#post.text}}</p>
          </div>
        {{/each}}
      </div>
    </script>

    <!--
    <script src="lib/derby-standalone.min.js"></script>
    -->
    <script src="//derbyjs.github.io/derby-standalone/dist/0.6.0-alpha25/derby-standalone.min.js"></script>
    <script src="index.js"></script>
  </body>
</html>