• 移植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的模块化方式,而又可以不经修改的运行在浏览器中。

  • 相关阅读:
    Redis分布式锁
    面试题2
    JVM面试题
    ThreadLocal相关代码和面试题
    Redis淘汰策略及LRU算法
    线上一些问题排查
    面试题1
    webmagic坑日志slf4j和springboot日志冲突
    URL using bad/illegal format or missing URL
    Git修复已发布版本的 Bug
  • 原文地址:https://www.cnblogs.com/zhengwenwei/p/2772835.html
Copyright © 2020-2023  润新知