移植Spine.js的开发模式到node.js环境

Spine.js是一个轻量级的MVC框架,它的核心代码是可以在浏览器l或者node.js里运行的,但是基于它的开发,例如创建Contact的数据模型,书上给的例子,是不能运行在node.js环境的。下面给出一种hack的方法,可以让它运行在node.js环境,以方便将逻辑和界面彻底分开,在node.js里就可以单独测试逻辑。

(function () {
    //require 
    var Spine;
    if(typeof require !== "undefined") {
        Spine = require("./spine.js");
        require("./spine.model.local.js");
    }
    else {
        Spine = this.Spine;
    }

    var Contact = Spine.Model.setup("Contact", ["first_name", "last_name", "email",
                                                "mobile", "work", "address", "notes"]);
    Contact.extend(Spine.Model.Local);

    Contact.selectAttributes = ["first_name", "last_name", "email", 
                                "mobile", "work", "address"];

    Contact.nameSort = function(a, b){ 
      if(a.first_name == b.first_name){
            if (a.first_name == b.first_name) return 0;
            return (a.first_name < b.first_name) ? -1 : 1;
        }

        return (a.first_name < b.first_name) ? -1 : 1;
    };

    Contact.include({
      selectAttributes: function(){
        var result = {};
        for (var i=0; i < this.parent.selectAttributes.length; i++) {
          var attr = this.parent.selectAttributes[i];
          result[attr] = this[attr];
        }
        return result;
      },
      
      fullName: function(){
        if ( !this.first_name && !this.last_name ) return;
        return(this.first_name + " " + this.last_name);
      }
    });
    
    //export
    if(typeof module !== "undefined") {
        module.exports = Contact;
    }
    else {
        this.Contact = Contact;
    }
})();

非常简单,就是require部分的处理和export部分的处理,这样就可以使用node.js的模块化方式,而又可以不经修改的运行在浏览器中。

原文地址:https://www.cnblogs.com/zhengwenwei/p/2772835.html