2008-09-20 65 views
2

我一直在玩Jaxer,雖然這個概念非常酷,但我無法弄清楚如何定義客戶端和服務器上都可用的對象。我找不到任何可以定義對象的例子。使用Jaxer時定義對象

我希望能夠定義一個對象,並指定哪些方法將在服務器上可用,哪些方法將在客戶端上可用,哪些將在客戶端上可用,但在服務器上執行(服務器-代理)。這可以在不使用三個單獨的<script>具有不同runat屬性的標籤的情況下完成嗎?我希望能夠在同一個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頁面是否正確?

回答

2

我在Aptana論壇(不再存在於網絡上)發現一篇文章,指出只能代表全球功能 ... Bummer。

但是,我一直在玩弄,您可以通過將您的代碼放入包含文件並使用<script>標籤和runat屬性來控制客戶端和服務器上可用的方法。

例如,我可以創建這個文件命名爲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",使他們可以提供給代理的功能。