Skip to content

Instantly share code, notes, and snippets.

@joshua-moore
Created January 5, 2015 17:00
Show Gist options
  • Save joshua-moore/015dd212d4c3eeec8454 to your computer and use it in GitHub Desktop.
Save joshua-moore/015dd212d4c3eeec8454 to your computer and use it in GitHub Desktop.
CanJS click counter example
<!DOCTYPE html>
<html lang="en">
<head>
<title>CanJS - Click counter</title>
<style type="text/css">
.zero {
color: #aaa;
font-weight: bold;
}
.positive {
color: #0a0;
font-weight: bold;
}
.negative {
color: #a00;
font-weight: bold;
}
</style>
</head>
<body>
<script type="text/mustache" id="app">
<my-counter><br />This is just my example component. It demonstrates using a template, holding state, reacting to user input, and using helpers to format the template output.</my-counter>
</script>
<script type="text/mustache" id="counter-template">
<strong>{{title}}</strong><br />
<button can-click="plus">+</button>
<button can-click="minus">-</button>
Counter: <span {{counterClass}}>{{count}}</span>
<content />
</script>
<div id="out"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
<script src="http://canjs.com/release/latest/can.jquery.js"></script>
<script type="text/javascript">
$(function() {
can.Component.extend({
tag: 'my-counter',
scope: {
title: 'Silly counter',
count: 0,
plus: function() {
this.attr('count', this.attr('count')+1);
},
minus: function() {
this.attr('count', this.attr('count')-1);
}
},
template: can.view('counter-template'),
helpers: {
counterClass: function(options) {
if (this.attr('count') == 0) return 'class="zero"';
if (this.attr('count') > 0) return 'class="positive"'
if (this.attr('count') < 0) return 'class="negative"'
}
}
});
// render our application
$("#out").html(can.view('app', {}));
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment