Skip to content

jhewlett/data-bind.lite

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

data-bind.lite

Lightweight data-binding library. Weighs in at just under 3kb minified and gzipped.

Declarative syntax:

Declaring a scope:

<div data-scope="scope">
  ...
<div>

Any expressions within that element have the context of the "scope" model.

Binding to values:

<p data-bind="fullName"></p>
<input type="checkbox" data-bind="checked">

Binding to classes:

<p data-class="myStyle"></p>

Binding to click events:

<button data-click="addAlias(alias)">Add alias</button>

Binding to enter key press:

<input data-enter="addAlias(alias)" type="text" data-bind="alias">

Repeating elements:

<ul id="aliases" data-foreach="alias in aliases">
  <li data-bind="alias.title"></li>
</ul>

Model definition

Declaring a scope:

var model = new DataBind.Model('scope');

Defining an attribute:

model.attr('firstName', 'Justin');
model.attr('items', {title: 'items', arr: [1, 2]});

Defining a computed property:

model.computed('fullName' function() {
  return this.get('firstName') + ' ' + this.get('lastName'); 
});

Computed properties are automatically updated when any of their underlying properties change.

Defining an action:

model.action('addItem', function(item) {
    this.get('items').push(item);
});

The return value of actions will be ignored.

Binding the model:

var binder = new DataBind.Binder(model);
binder.bind();

Full example

Html:

<div data-scope="aboutMe">
  <strong>Full name:</strong> <span data-bind="fullName"></span>
  <br>
  <strong>Also known as:</strong>
  <ul data-foreach="alias in aliases">
    <li>
      <span data-bind="alias.title" data-class="alias.style"></span>
      <button data-click="removeItem(alias)">x</button>
    </li>
  </ul>

  <input data-enter="addAlias()" type="text" data-bind="newAlias">

  <button data-click="addAlias()">Add Alias</button>
</div>

Javascript:

var model = new DataBind.Model('aboutMe');

model.attr('firstName', 'Justin');
model.attr('lastName', 'Hewlett');
model.attr('aliases', [{title: 'Jus', style: 'italic'}, {title: 'Justy', style: 'underline'}]);
model.attr('newAlias', '');

model.computed('fullName', function() {
  return this.get('firstName') + ' ' + this.get('lastName');
});

model.action('addAlias', function() {
  this.get('aliases').push({title: this.get('newAlias'), style: 'underline'});
  this.attr('newAlias', '');
});

model.action('removeItem', function(item) {
    this.get('aliases').remove(item);
});

var binder = new DataBind.Binder(model);
binder.bind();

Css:

.underline {
  text-decoration: underline;
}

.italic {
  font-style: italic;
}

Results:

About

Tiny 2-way data-binding library for web apps

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published