-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo2.html
78 lines (71 loc) · 2.23 KB
/
demo2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>
<html>
<meta charset="GB18030">
<head>
<title>Model</title>
</head>
<body>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script>
(function ($) {
Man = Backbone.Model.extend({
url:'/man/',
initialize: function(){
console.log("hello world");
//初始化时绑定监听
this.bind("change:name",function(){
var name = this.get("name");
console.log("你改变了name属性为:" + name);
});
this.bind("error",function(model,error){
console.log(error);
});
this.bind("invalid",function(model,error){
console.log(model);
console.log(error);
});
},
defaults: {
name:'盖伦',
age: '38'
},
validate:function(attributes){
if(attributes.name == '') {
return "name不能为空!";
}
},
aboutMe: function(){
return '我叫' + this.get('name') + ',今年' + this.get('age') + '岁';
}
});
var man = new Man;
//alert(man.get('name'));
//alert(man.aboutMe());
man.set({name:'提莫'}) //触发绑定的change事件,alert。
man.set({name:''}); //默认set时不进行验证
//man.set({name:''}, {'validate':true}); //手动触发验证, set时会触发
man.save(); //会发送POST到模型对应的url,数据格式为json{"name":"盖伦","age":38}
//然后接着就是从服务器端获取数据使用方法fetch([options])
var man1 = new Man;
//第一种情况,如果直接使用fetch方法,那么他会发送get请求到你model的url中,
//你在服务器端可以通过判断是get还是post来进行对应的操作。
man1.fetch();
//第二种情况,在fetch中加入参数,如下:
man1.fetch({url:'/child/'});
//这样,就会发送get请求到/getmans/这个url中,
//服务器返回的结果样式应该是对应的json格式数据,同save时POST过去的格式。
//不过接受服务器端返回的数据方法是这样的:
man1.fetch({url:'/child/',success:function(model,response){
console.log('success');
//model为获取到的数据
console.log(model.get('name'));
},error:function(){
//当返回格式不正确或者是非json数据时,会执行此方法
console.log('error');
}})
})(jQuery);
</script>
</html>