can
Version:
MIT-licensed, client-side, JavaScript framework that makes building rich web applications easy.
122 lines (113 loc) • 2.8 kB
HTML
<html lang="en">
<head>
<title>Model Convert Demo</title>
<style type='text/css'>
body {font-family: verdana}
li {border: solid 1px gray; padding: 5px; }
li a {color: red; font-weight: bold;}
p {width: 400px;}
</style>
</head>
<body>
<div id="demo-html">
<div id="contacts"></div>
</div>
<script type='text/javascript' src='../../node_modules/steal/steal.js' main="@empty"></script>
<script type='text/javascript' id="demo-source">
steal(function() {
steal.config({
root: '../../../'
});
}).then('can/map/attributes', 'can/model','can/util/fixture')
.then(function(){
// simulate ajax response with fixtures
can.fixture("/contacts.json", function(){
return [{
'id': 1,
'name' : 'Justin Meyer',
'birthday': '1982-10-20',
tasks : [{
id: 1,
title: "write up model layer",
due: "2010-10-5"
}]},{
'id': 2,
'name' : 'Brian Moschel',
'birthday': '1983-11-10',
tasks : [{
id: 2,
title: "write up funcunit",
due: "2009-5-1"
},{
id: 3,
title: "test funcunit",
due: "2010-3-15"}]
},{
'id': 3,
'name' : 'Bobby Joe',
'birthday': '1980-2-10'
}];
})
can.Model.convert.date = function(raw){
if(typeof raw == 'string'){
var matches = raw.match(/(\d+)-(\d+)-(\d+)/);
return new Date( +matches[1],
(+matches[2])-1,
+matches[3] );
}else if(raw instanceof Date){
return raw;
}
};
// A task model that has a date
var Task = can.Model({
attributes : {
due : 'date'
}
},{
weeksPastDue : function(){
return Math.round( (new Date() - this.due) /
(1000*60*60*24*7 ) );
}
});
// A contact model that has many tasks
var Contact = can.Model({
attributes : {
birthday : 'date',
tasks: Task
},
findAll : "/contacts.json"
},{
ageThisYear : function(){
return new Date().getFullYear() -
this.birthday.getFullYear()
},
getBirthday : function(){
return ""+this.birthday.getFullYear()+
"-"+(this.birthday.getMonth()+1)+
"-"+this.birthday.getDate();
}
});
// Get all contacts and put them on the page
Contact.findAll({}).done(function(contacts){
var contactsEl = can.$('#contacts');
can.each(contacts, function(contact){
var li = can.$('<li>')
.html(contact.name + " "+ contact.ageThisYear())
.appendTo(contactsEl);
var ul = can.$("<ul>");
var tasks = contact.attr('tasks')
if(tasks){
tasks.each(function(){
ul.append('<li>'+this.title+" "
+this.weeksPastDue()+'</li>')
});
}
ul.appendTo(li)
});
});
});
</script>
</body>
</html>