2012-08-08 73 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 
相关问题