Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Backbone.jsのModel機能をローカルで実現できるようにしたsample
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
<script type="text/javascript" src="https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.min.js"></script>
<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/javascript">
var ExampleModel = Backbone.Model.extend({
defaults:{ name: "anonimous"},
validate: function(attrs){
if(attrs.age < 0){
return "age must be positive";
}
}
});
var ExampleCollection = Backbone.Collection.extend({
url: "/examples",
model: ExampleModel
});
jQuery.ajax = function(params){
console.log(params);
params.success(
[{id: 1,name: "takeshy",age: 36},{id: 2,name: "hoge",age: 22}]
);
};
jQuery(function() {
var sample = new ExampleModel({age: 0});
console.log(sample);
sample.on("error",function(obj,err){ console.log(err);});
sample.set({age: -1})
console.log(sample);
var collection = new ExampleCollection();
collection.fetch();
console.log(collection.toArray());
var model = collection.get(1)
model.on("change",function(){ $("#contents").html(model.get("age"))});
model.set("age",model.get("age")+1);
});
</script>
</head>
<body>
<div id="contents"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment