【问题标题】:Knockout, ViewModel inside an other object and data-bindingKnockout、ViewModel 在另一个对象中和数据绑定
【发布时间】:2023-04-11 03:47:01
【问题描述】:

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

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”中的数据?

【问题讨论】:

    标签: javascript data-binding knockout.js


    【解决方案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>
    

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

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

    【讨论】:

      猜你喜欢
      • 2015-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多