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

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

问题描述

如果一页上有多个视图模型,如何确保它们可以保持同步? 例如,如果添加了一个项目或在一个视图模型上单击了一个按钮,而您又希望另一个视图模型对该更改敏感,则Knockout可以本机管理,还是最好使用某些消息传递或发布/订阅体系结构. /p>

我希望不必管理模型之间的可观测对象.

解决方案

Knockout 2.0确实包含使您可以进行基本发布/订阅的功能.这是两个视图模型通过调解器进行通信的示例.

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"));

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

某些情况下,邮箱不一定是全局的,可以传递到视图模型构造函数中,也可以仅在自执行函数中创建.

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

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

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 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.

Sample: http://jsfiddle.net/rniemeyer/z7KgM/

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

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

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