backbone学习第二天

本文通过一个简单的Backbone.js实例介绍了如何使用Model、View和Collection来构建基本的前端应用。用户可以输入自己所在的星球名称,应用将显示一条欢迎消息。
<!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的代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值