简体   繁体   English

Knockout.js - 如何更改viewmodel

[英]Knockout.js - How to change the viewmodel

I'm trying to change the view model which is bound to some part of a DOM template (instead of changing the values of the view model) but I just can't figure out how or if it's even possible 我正在尝试更改绑定到DOM模板某些部分的视图模型(而不是更改视图模型的值)但我无法弄清楚它是如何或是否可能

Here's the scenario: 这是场景:

  • Create a new View Model object 创建一个新的View Model对象
  • Bind it (eg applyBindings(myViewModel) 绑定它(例如applyBindings(myViewModel)
  • Create another View Model object 创建另一个View Model对象
  • Bind the new object to the same part of the DOM so all elements are now bound to the new object. 将新对象绑定到DOM的同一部分,以便所有元素现在都绑定到新对象。

I want to do the equivalent of changing the value of DataContext of a control in WPF (on which KO's MVVM pattern is based) 我想做相当于改变WPF中控件的DataContext的值(KO的MVVM模式所基于的)

The reason for this is that I'm trying to use the same view model for both the representation of the object in a list and the representation of the object in its own view, so I already have a view model for all objects being shown in the list. 这样做的原因是我试图对列表中对象的表示和对象在其自己的视图中的表示使用相同的视图模型,因此我已经有一个视图模型用于显示的所有对象列表。

There are other workarounds but I think this would be the most elegant way to do it. 还有其他解决方法,但我认为这将是最优雅的方式。

There are two way of working with multiple viewmodel. 使用多个viewmodel有两种方法。 The first way is to do multiple binding like @nathan gonzalez said. 第一种方式是做多个绑定,比如@nathan gonzalez说。 You should do binding up your viewmodels. 您应该绑定视图模型。 However this complicates things a bit. 然而,这使事情变得复杂。 Therefore difficult to manage. 因此难以管理。

The second way is to use master viewmodel. 第二种方法是使用主视图模型。 I would recommend this. 我会推荐这个。

http://jsfiddle.net/sinanakyazici/e29EZ/10/ http://jsfiddle.net/sinanakyazici/e29EZ/10/

<div data-bind="with: mainvm">
    <span data-bind="text: prop, click : action"></span>
</div>

var vm = function(value)
{
    this.prop = ko.observable(value);
    var self = this;
    this.action = function() {
        console.log("clicked: " + self.prop());
    }
}

var master = {
    mainvm : ko.observable(null)
}

master.mainvm(new vm('viewmodel 1'));
master.mainvm(new vm('viewmodel 2'));
ko.applyBindings(master);

so ko.applyBindings() should cover this for you. 所以ko.applyBindings()应该为你报道。 you can pass in a 2nd parameter that tells which top level element to apply the bindings to, like so: 你可以传入第二个参数,告诉哪个顶级元素应用绑定,如下所示:

 ko.applyBindings(myExistingViewModel, $('#someElementId')[0]);

you may want to clean the elements first though, like this: 你可能想先清理元素,如下所示:

ko.cleanNode($('#someElementId')[0]);

this completely removes the bindings and clears the in memory data for that element and its children bindings. 这将完全删除绑定并清除该元素及其子绑定的内存数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM