gpt4 book ai didi

javascript - 点击按钮时,knockout.js 在 vi​​ewmodel2 中从 viewmodel1 进行更改

转载 作者:行者123 更新时间:2023-12-03 04:38:03 26 4
gpt4 key购买 nike

这是我的代码

<h4>View Model 1 </h4>
<div data-bind="with: viewModel1">
<input data-bind="value: messageForVM2" />
<button data-bind="click:abc">btn</button>
</div>

<h4>View Model 2</h4>
<div data-bind="with: viewModel2">
<p data-bind="text:message">
</p>

<p data-bind="text:message2">
</p>
</div>

这是 View 模型

var shouter = new ko.subscribable();    
var viewModel1 = function()
{
this.firstName = ko.observable("Wrapcode");
this.messageForVM2 = ko.observable("Hello from first view model");
this.messageForVM2.subscribe(function(newValue) {
shouter.notifySubscribers(newValue, "messageToPublish");
});
this.message = ko.observable("Hello this is vm1");

this.abc= function ()
{
alert("abc");
};
};

var viewModel2 = function(vm1){
this.message = ko.observable("Start typing message in input box above");
shouter.subscribe(function(newValue) {
this.message(newValue);
}, this, "messageToPublish");
};


var masterVM = (function(){
var self= this;
self.viewModel1 = new viewModel1();
self.viewModel2 = new viewModel2();
})();

ko.applyBindings(masterVM)

我在 viewmodel1 中有一个按钮单击事件 abc。我如何通过单击 viewmodel 1 中的按钮来更改 viewmodel2 的 message2。

最佳答案

首先,您需要在 ViewModel2 中提供 message2 对象。然后您可以将父对象传递给子对象以获取对其的引用。

var viewModel1 = function(parentObject)
{
var self = this;
self.parent = parentObject;
...
...
this.abc = function () {
self.parent.viewModel2.message2("Change the message from ViewModel1")
};
};

var viewModel2 = function(vm1){
this.message2 = ko.observable("");
...
};

var masterVM = (function(){
var self = this;
self.viewModel1 = new viewModel1(self);
self.viewModel2 = new viewModel2();
})();

ko.applyBindings(masterVM)

这是一个示例

   
function viewModel1(parentObject) {
var self = this;
self.parent = parentObject;
self.total = ko.observable(0);
self.clickAction = function() {
self.total(self.total() + 1);
self.parent.viewModel2.message(self.total() + "x modified from ViewModel1");
};
}
function viewModel2() {
var self = this;
self.message = ko.observable("Default message of ViewModel2");
}
function viewModel() {
var self = this;
self.viewModel1 = new viewModel1(self);
self.viewModel2 = new viewModel2();
}
ko.applyBindings(new viewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="with: viewModel1">
<button data-bind="click:clickAction">Modify ViewModel2 message!</button>
</div>

<div data-bind="with: viewModel2">
<div>Message:</div>
<div data-bind="text: message"></div>
</div>

关于javascript - 点击按钮时,knockout.js 在 vi​​ewmodel2 中从 viewmodel1 进行更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com