2012-08-08 72 views
1

我正在做一個遊戲的JavaScript應用程序,目標是爲MMORPG製作一個「構建計算器」。我想將視圖與已存儲在我的應用程序中的數據同步。我搜索和測試不同的框架,和淘汰賽-JS似乎對我來說是最好的解決辦法Knockout,ViewModel內部的其他對象和數據綁定

HTML:

<script> 
var simulatorTool = new SimulatorTool(); 
</script> 

<body> 
<p data-bind="text: test"> </p> 
<p data-bind="text: test2"> </p> 
</body> 

的Javascript工具:

function SimulatorTool() 
{ 

meSim = this; 

this.config = new Config(); 
this.data = new Data(); 
this.stuff = new Stuff(); 
this.traits = new Traits(); 
this.view = new AppViewModel(); 
$(function(){ 
    ko.applyBindings(meSim.view); 
}); 

... functions 

} 

視圖模型:

function AppViewModel() { 
    this.test = "Test!"; 

    this.test2 = ko.computed(function() { 
     return meSim.data.selectedData['profession'] 
    }, this); 
} 

問題是,我不知道如何將html綁定到其他對象中的視圖。我甚至不知道是否有可能。我想要做這樣的事情

<p data-bind="simulatorTool.view, text: test"> </p> 

如果沒有,我怎麼能訪問到內「SimulatorTool」的數據,如果畫面從應用程序分離?

回答

-1

我想你想要做的是這樣的事情 - 讓我們在simulator_tool.js說:

var SimulatorTool = SimulatorTool || {}; 

SimulatorTool.ViewModel = function(initialData){ 
    //bindings etc 
}; 

SimulatorTool.Start - function(initialData){ 
    var viewModel = SimulatorTool.ViewModel(initialData); 
    ko.applyBindings(viewModel); 
    return viewModel //if you want to play with it in the console... 
}; 

然後,您的網頁上:

<script> 
$().ready(function()){ 

    var payload = @Html.Raw(ViewBag.SimulatorJSON); 
    SimulatorTool.Start(payload); 

} 
</script> 

理想情況下,你可能有一個應用程序。 js文件的SimulatorTool命名空間已經設置,所以你可以擺脫聲明。我不知道JSON轉儲是否已經設置配置,或者它是否設置在其他地方 - 但通常這都屬於使用函數或whatnot的其自己的命名空間:

SimulatorTool.Config = { 

} 

SimulatorTool.Stuff = { 

} 
//etc 
相關問題