【问题标题】:Using Knockout to bind different models to different sections on a page使用 Knockout 将不同的模型绑定到页面上的不同部分
【发布时间】:2013-10-28 16:20:27
【问题描述】:

我在我的 asp.net 应用程序中使用了 knockout javascript 库。

对于淘汰赛,我使用 ko 对象和 applyBindings() 方法来绑定它。现在我想将两个淘汰对象绑定到两个不同的用户界面部分。如何使用第二个淘汰对象或第二个数据源,以便在第二部分中使用它?

【问题讨论】:

  • 您能否提供一个具体的案例来满足您的需要,可能还有一些代码示例?
  • 考虑这个例子:learn.knockoutjs.com/#/?tutorial=loadingsaving 如你所见,使用 ko.applyBindings(new TaskListViewModel());绑定数据的代码。现在我的页面中有另一个部分,它使用另一个对象和另一个从服务器加载/保存数据。如何做第二个,因为似乎只有一个可用的淘汰对象。

标签: knockout.js


【解决方案1】:

您可以轻松地将不同的绑定应用到 HTML 代码的不同部分。

如果你有这样的结构:

<div id="one"></div>
<div id="two"></div>

只要做这样的事情:

ko.applyBindings(viewModelOne, document.getElementById('one'));
ko.applyBindings(viewModelTwo, document.getElementById('two'));

如果你有这样的结构:

<div id="one">
    <div id="two"></div>
</div>

您可以使用controlsDescendantBindings 标志来告诉knockout 不理会某个子元素。在自定义绑定中使用它,如下所示:

ko.bindingHandlers.stopBinding = {
    init: function() {
        return { controlsDescendantBindings: true };
    }
};

并像这样使用它:

<div id="one">
    <div data-bind="stopBinding: true">
        <div id="two"></div>
    </div>
</div>

我用 stopBinding 函数包围了第二个 div。这允许您像这样调用相同的 applyBindings 代码:

ko.applyBindings(viewModelOne, document.getElementById('one'));
ko.applyBindings(viewModelTwo, document.getElementById('two'));

参考:http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

【讨论】:

  • 您在所有四个 applyBindings 调用中都忘记了最后的 )
  • 已编辑,谢谢。当你在凌晨 3 点回答问题时,就会发生这种情况。
  • 不错!不知道controlsDescendantBindings
猜你喜欢
  • 2013-01-21
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
相关资源
最近更新 更多