在 Knockout 中链接/同步视图模型的最佳方法是什么? [英] Whats the best way of linking/synchronising view models in Knockout?

查看:23
本文介绍了在 Knockout 中链接/同步视图模型的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在一个页面上有多个视图模型,您如何确保可以使它们保持同步?例如,如果添加了一个项目或在一个视图模型上单击了一个按钮,并且您希望另一个视图模型对该更改敏感,那么 Knockout 是否可以在本机进行管理,或者最好使用一些消息传递或发布/订阅架构.

If you have several view models on one page, how do you ensure that you can keep them synced? For example, if one item is added or a button clicked on one view model and you want the other view model to be sensitive to that change, can Knockout manage this natively or is it better to use some messaging or pub/sub architecture.

我不想在模型之间管理可观察对象.

I want to stay away from having to manage observables between models.

推荐答案

Knockout 2.0 确实包含可让您执行基本发布/订阅的功能.这是一个示例,其中两个视图模型通过中介进行通信.

Knockout 2.0 does include functionality that lets you do basic pub/sub. Here is a sample where two view models communicate through a mediator.

var postbox = new ko.subscribable();

var ViewModelOne = function() {
    this.items = ko.observableArray(["one", "two", "three"]);
    this.selectedItem = ko.observable();
    this.selectedItem.subscribe(function(newValue) {
        postbox.notifySubscribers(newValue, "selected");
    });
};

var ViewModelTwo = function() {
    this.content = ko.observable();
    postbox.subscribe(function(newValue) {
        this.content(newValue + " content");
    }, this, "selected");
};

ko.applyBindings(new ViewModelOne(), document.getElementById("choices"));
ko.applyBindings(new ViewModelTwo(), document.getElementById("content"));

第一个视图模型通过邮箱通知特定主题,第二个视图模型订阅该主题.它们之间没有直接的依赖关系.

The first view model notifies through the postbox on a specific topic and the second view model subscribes to that topic. They have no direct dependency on each other.

当然,邮箱不需要是全局的,可以传递到视图模型构造函数中,或者只是在自执行函数中创建.

Certainly the postbox would not need to be global and could be passed into the view model constructor functions or just created inside a self-executing function.

示例:http://jsfiddle.net/rniemeyer/z7KgM/

此外,postbox 可以只是一个 ko.observable(包括 ko.subscribable 函数).

Also, the postbox could just be a ko.observable (which includes the ko.subscribable functions).

这篇关于在 Knockout 中链接/同步视图模型的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆