Code Monkey

于工开始移山

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Restful 服务调用

  Collection.fetch() - 请求集合

  Model.save() - 新增或修改模型(根据 Model.isNew() 方法判断操作类型)

  Model.destroy() - 删除模型

  Model.sync() - 请求的执行方法, fetch(), save(), destroy() 都调用其方法进行操作请求

(function ($) {
    //define -------------------------------
    var Product = Backbone.Model.extend({
        idAttribute: "Id",
        url: "/ProductService.svc/Product"//Rest URL
    });
    var ProductCollection = Backbone.Collection.extend({
        model: Product,
        url: "/ProductService.svc/products"//rest URL
    });
    var ProductListView = Backbone.View.extend({
        tagName: "ul",
        events: {
            "click": "selectName"
        },
        selectName: function (e) {
            if (e.target.nodeName === "A") {
                this.collection.trigger("selected", this.collection.get($(e.target).attr("data-id")));
            }
        },
        render: function () {
            this.$el.html(_.map(this.collection.models, function (model) {
                return "<li><a href='javascript:;' data-id='" + model.get('Id') + "'>" + model.get('Name') + "</a></li>";
            }));
            return this;
        }
    });
    var EditPanelView = Backbone.View.extend({
        tagName: "div",
        events: {
            "click .btnUpdate": "update",
            "click .btnCreate": "create",
            "click .btnDestroy": "destroy"
        },
        update: function () {
            /* Backbone MethodMap
                create: "POST"
                delete: "DELETE"
                patch: "PATCH"
                read: "GET"
                update: "PUT"
            */
            /* 参数二
                {
                    patch:true // is PATCH method
                    wait:true //同步方法
                }
            */
            this.model.save({
                'Name': this.$el.find("input[type='textBox']")[0].value
            }, { success: this.success, operType: "update" });
        },
        create: function () {
            //Collection.create() 方法回调用 Model.save() 方法
            new Product({
                Name: this.$el.find("input[type='textBox']")[0].value
            }).save(null, { success: this.success, operType: "create" });
        },
        destroy: function () {
            this.model.destroy({ success: this.success, url: this.model.url + "/" + this.model.get('Id'), operType: "destroy" });
        },
        success: function (model, data, options) {
            //operate callback
            switch (options.operType) {//operType 自定义属性,标识回调函数的操作类型
                case "create":
                    break;
                case "update":
                    break;
                case "destroy":
                    break;
                default:
            }
        },
        render: function () {
            this.$el.html("<label>Name:</label><input type='textBox' value='" + this.model.get("Name") + "'>" +
                "<input type='button' class='btnUpdate' value='Update'/>" +
                "<input type='button' class='btnCreate' value='Create'/>" +
                "<input type='button' class='btnDestroy' value='Destroy'/>");
            return this;
        }
    });
    $(function () {
        //instance ---------------------------------
        var productCollection = new ProductCollection();
        //fetch() 方法获取数据    [success and error 是成功的和异常的回调函数]
        /* fetch, save, destroy 方法都会调用 sync() 方法来执行 HTTP 请求 */
        /* sync() 方法参数
            method - [create, update, patch, delete, read]
            model - 需要同步的模型或集合
            options - $.ajax 所需要的参数
        */
        productCollection.fetch({
            success: function (collection, response, options) {
                collection.on("selected", function (model) {
                    $("#divEdit").html(new EditPanelView({ model: model }).render().el);
                });
                $('body').html(new ProductListView({ collection: collection }).render().el);
                $('body').append($("<div id='divEdit'></div>"));
            },
            error: function (collection, response, options) {
                alert('error');
            }
        });
    });
})(jQuery);

 使用 HTML 5 本地存储

(function ($) {
    //依赖 backbone.localStorage.js
    //https://github.com/jeromegn/backbone.localStorage

    //define --------------------------
    var UserModel = Backbone.Model.extend();
    /* Backbone 的 LocalStorage Adapter 重写了 Backbone.sync() 方法。
        当模型关联上集合后,模型的 save() 方法可正常使用。
    */
    /* 注:创建模型时,不要调用 Model.save() 方法,而是调用 Collection.create() 方法 */
    var UserCollection = Backbone.Collection.extend({
        model: UserModel,
        //定义本地存储模型对象 [参数唯一性]
        localStorage: new Backbone.LocalStorage("userCollection")
    });
})(jQuery);
View Code
posted on 2014-08-13 16:40  MSchina  阅读(161)  评论(0编辑  收藏  举报