一个项目需要同时访问多个AVOS cloud的App的数据,但官方的JS SDK在init完后只生成了一个global的object AV,这使得没法直接连接多个App获取数据。所以我就写了小段代码来解决这个问题。为了简单解决CORS,我把AV.js保存到本地了。

浏览器版本

var AVContexts = {
    App1: null,
    App2: null
}

var ContextLoader = function (appId, appKey) {
    this.AV = null;
    this.runInThis = function (script) {
        eval(this.script);
        this.AV.initialize(appId, appKey);
    }
    this.loadContext = function (appId, appKey) {
        $.ajax({
            url: 'js/av.js',
            dataType: "text",
            context: this
        }).done(function (data) {
            this.script = data;
            this.runInThis.call(this);
        }).fail(function () {
            console.log('failed');
        });
    }
    this.loadContext(appId, appKey);
}

AVContexts.App1 = new ContextLoader(
        "[appid]",
        "[appkey]"
);
AVContexts.App2 = new ContextLoader(
        "[appid]",
        "[appkey]"
);

// Do something
var TestObject = AVContexts.App1.AV.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({foo: "bar"}, {
                success: function (object) {
                    alert("AVOS Cloud works!");
                }
            });

Nodejs版本

替换其中的ContextLoader就好了

var ContextLoader = function (appId, appKey) {
    this.AV = null;
    this.runInThis = function (script) {
        eval(this.script);
        this.AV.initialize(appId, appKey);
    }
    this.loadContext = function (appId, appKey) {
        var code = fs.readFileSync('cloud/lib/av.js', {encoding: 'utf8'});
        this.script = code;
        this.runInThis.call(this);
    }
    this.loadContext(appId, appKey);
}

fxp
462 声望59 粉丝

coder in action


引用和评论

0 条评论