使用Jaxer时定义对象

时间:2020-03-06 14:29:46  来源:igfitidea点击:

我一直在和Jaxer一起玩,虽然这个概念很酷,但是我无法弄清楚如何定义在客户端和服务器上都可用的对象。我找不到的所有示例都没有定义对象。

我希望能够定义一个对象并指定哪些方法在服务器上可用,哪些方法在客户端上可用,哪些方法在客户端上可用但在服务器上执行(服务器代理)。是否可以在不使用具有不同runat属性的三个独立<script>标记的情况下完成此操作?我希望能够在同一个js文件中定义所有方法,并且用三个单独的标签在html中内联定义我的对象是不切实际的...

基本上,我希望能够在一个js文件中执行此操作:

function Person(name) {
    this.name = name || 'default';
}
Person.runat = 'both';

Person.clientStaticMethod = function () {
    log('client static method');
}
Person.clientStaticMethod.runat = 'client';

Person.serverStaticMethod = function() {
    log('server static method');
}
Person.serverStaticMethod.runat = 'server';

Person.proxyStaticMethod = function() {
    log('proxy static method');
}
Person.proxyStaticMethod.runat = 'server-proxy';

Person.prototype.clientMethod = function() {
    log('client method');
};
Person.prototype.clientMethod.runat = 'client';

Person.prototype.serverMethod = function() {
    log('server method');
};
Person.prototype.serverMethod.runat = 'server';

Person.prototype.proxyMethod = function() {
    log('proxy method');
}
Person.prototype.proxyMethod.runat = 'server-proxy';

另外,假设我能够做到这一点,如何将其正确地包含到html页面中?

解决方案

我在Aptana论坛上找到了一个帖子(网络上不再存在),指出只能代理全局函数... Bummer。

但是,我一直在玩耍,我们可以通过将代码放在包含文件中,并使用带有runat属性的<script>标记,来控制哪些方法可以在客户端和服务器上使用。

例如,我可以创建名为Person.js.inc的文件:

<script runat="both">

    function Person(name) {
        this.name = name || 'default';
    }

</script>

<script runat="server">

    Person.prototype.serverMethod = function() {
        return 'server method (' + this.name + ')';
    };

    Person.serverStaticMethod = function(person) {
        return 'server static method (' + person.name + ')';
    }

    // This is a proxied function.  It will be available on the server and
    // a proxy function will be set up on the client.  Note that it must be 
    // declared globally.
    function SavePerson(person) {
        return 'proxied method (' + person.name + ')';
    }
    SavePerson.proxy = true;

</script>

<script runat="client">

    Person.prototype.clientMethod = function() {
        return 'client method (' + this.name + ')';
    };

    Person.clientStaticMethod = function (person) {
        return 'client static method (' + person.name + ')';
    }

</script>

我可以使用以下方法将其包括在页面上:

<jaxer:include src="People.js.inc"></jaxer:include>

不幸的是,由于所有脚本都已内联,因此我失去了为客户端脚本浏览器缓存的优势。我能找到的避免该问题的唯一技术是将客户端方法,服务器方法和共享方法拆分为它们自己的js文件:

<script src="Person.shared.js" runat="both" autoload="true"></script>
<script src="Person.server.js" runat="server" autoload="true"></script>
<script src="Person.client.js" runat="client"></script>

而且,到那时,我还可以将代理函数也拆分到自己的文件中...

<script src="Person.proxies.js" runat="server-proxy"></script>

请注意,我在共享和服务器脚本上使用了" autoload =" true"`,以便代理功能可以使用它们。