首页 > 代码库 > 2014/08/14 – Backbonejs

2014/08/14 – Backbonejs

[来自: Backbone.js 开发秘笈 第8章]

相关技术:

1. 使用 Require.js 组织项目结构

文件结构:

index.html

lib/

  underscore.js

  jquery.js

  backbone.js

js/

  app.js

  userDefine.js

 

index.html:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <title></title>    </head><!-- data-main 程序入口点 --><script src="lib/require.js" data-main="js/app"></script><body></body></html>

app.js:

//require 配置信息require.config({    //定义库别名    paths: {        jquery: "../lib/jquery",        underscore: "../lib/underscore",        backbone: "../lib/backbone"    },    //定义模块间关系    shim: {        backbone: {            deps: ["jquery", "underscore"],//依赖关系            exports: "Backbone"//非 AMD 标准类库定义        },        underscore: {            exports: "_"        },        jquery: {            exports: "$"        }    }});//require() 方法启动应用程序require(["jquery", "../js/userDefine"], function ($, user) {    $(function () {        $("body").html(new user.userListView({            collection: new user.userCollection([                { id: 1, name: "yoyo" },                { id: 4, name: "ramos" },                { id: 7, name: "ronaldo" }            ])        }).render().el);    });});

userDefine.js:

//AMD 标准模块定义    [参数一为加载模块数组,参数二为模块加载后的回调函数]define(["jquery", "backbone", "underscore"], function ($, Backbone, _) {    return {        userCollection: Backbone.Collection.extend({            model: Backbone.Model.extend()        })        ,        userListView: Backbone.View.extend({            tagName: "ul",            render: function () {                this.$el.html(_.map(this.collection.models, function (model) {                    return "<li><a href=‘javascript:;‘>" + model.get("name") + "</a></li>";                }));                return this;            }        })    };});