backbone学习第二天

来源:互联网 发布:mac能玩游戏 编辑:程序博客网 时间:2024/04/28 20:26
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>the5fire.com-backbone.js-Hello World</title>
</head><body>
<script src="http://the5fireblog.b0.upaiyun.com/staticfile/jquery-1.10.2.js"></script>
<script src="http://the5fireblog.b0.upaiyun.com/staticfile/underscore.js"></script>
<script src="http://the5fireblog.b0.upaiyun.com/staticfile/backbone.js"></script>
<script>
(function ($) {
    World = Backbone.Model.extend({
        //创建一个 World 的对象,拥有 name 属性
        name: null
    });
    Worlds = Backbone.Collection.extend({
    //World 对象的集合
        initialize: function (models, options) {
            this.bind("add", options.view.addOneWorld);//bind函数在事件触发时引发addOneWorld
        }
    });
    AppView = Backbone.View.extend({
        el: $("body"),
        initialize: function () {//构造函数,实例化一个 World 集合类,并且以字典方式传入 AppView的对象
            this.worlds = new Worlds(null, { view : this })
        },events: {
            "click #check": "checkIn", //事件绑定,绑定 Dom 中 id 为 check的元素
        },
        checkIn: function () {
            var world_name = prompt("请问,您是哪星人?");
            if(world_name == "") world_name = '未知';
            var world = new World({ name: world_name });
            this.worlds.add(world);
        },
        addOneWorld: function(model) {
            $("#world-list").append("<li>这里是来自 <b>" + model.get('name')+ "</b> 星球的问候:hello world!</li>");
        }
    });//实例化 AppView
    var appview = new AppView;
})(jQuery);
</script>
    <button id="check" class="" >确定</button>
    <span id="world-list"></span>
</body>
</html>

一段使用model view collection的代码
0 0