挖空、视图模型位于其他对象和数据绑定中

Knockout, ViewModel inside an other object and data-binding

本文关键字:其他 对象 数据绑定 视图 模型 于其他 挖空      更新时间:2023-09-26

我正在为一个游戏做一个javascript应用程序,目标是为MMORPG制作一个"构建计算器"。我想将视图与应用程序中已存储的数据同步。我搜索并测试了不同的框架,而 knockout-js 似乎是我的最佳解决方案

目录:

<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>

如果没有,如果视图与应用程序分离,我如何访问"模拟器工具"中的数据?

我认为你想做的是这样的 - 让我们在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>

理想情况下,您可能有一个已经设置了 SimulatorTool 命名空间的应用程序.js文件,因此您可以摆脱声明。我不知道 JSON 转储是否已经设置了配置,或者它是否在其他地方设置了 - 但通常这一切都属于它自己的命名空间,使用函数或其他东西:

SimulatorTool.Config = {
}
SimulatorTool.Stuff = {
}
//etc