KnockoutJS和PubSub更新视图之间的可观察数组 [英] KnockoutJS and PubSub to update observable array between views

查看:84
本文介绍了KnockoutJS和PubSub更新视图之间的可观察数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个modalviews-MyModalViewA(父级)和MyModalViewB(子级).

I have two modalviews - MyModalViewA (parent) and MyModalViewB (child).

MyModalViewA生成MyModalViewB,作为自定义绑定,并且具有我需要更新的可观察数组.它看起来像:

MyModalViewA spawns MyModalViewB, as custom binding, as well has observable array which I need to update. And it looks like:

(function () {

            'use strict';

            var
                window = __webpack_require__(/*! window */ 10),
                _ = __webpack_require__(/*! _ */ 2),
                $ = __webpack_require__(/*! $ */ 12),
                ko = __webpack_require__(/*! ko */ 3),
                key = __webpack_require__(/*! key */ 16),

                Enums = __webpack_require__(/*! Common/Enums */ 4),
                Utils = __webpack_require__(/*! Common/Utils */ 1),

                Links = __webpack_require__(/*! Common/Links */ 13),
                Remote = __webpack_require__(/*! Remote/User/Ajax */ 14),

                kn = __webpack_require__(/*! Knoin/Knoin */ 5),
                AbstractView = __webpack_require__(/*! Knoin/AbstractView */ 11),
                AttachmentModel = __webpack_require__(/*! Model/Attachment */ 86)
            ;

    function MyModalViewA()
    {
       ...some observables...
       //data response which must be updated
       this.rows= ko.observableArray([]);

       this.getResults = Utils.createCommand(this, function() 
       {
         kn.showScreenPopup(__webpack_require__(/*! View/Popup/SearchUsers */ 171),[oData]);
       }
    }

 kn.constructorEnd(this);
}

module.exports = MyModelViewA;

}());

然后MyModelViewB:

(function () {

            'use strict';

            var
                window = __webpack_require__(/*! window */ 10),
                _ = __webpack_require__(/*! _ */ 2),
                $ = __webpack_require__(/*! $ */ 12),
                ko = __webpack_require__(/*! ko */ 3),
                key = __webpack_require__(/*! key */ 16),

                Enums = __webpack_require__(/*! Common/Enums */ 4),
                Utils = __webpack_require__(/*! Common/Utils */ 1),

                Links = __webpack_require__(/*! Common/Links */ 13),
                Remote = __webpack_require__(/*! Remote/User/Ajax */ 14),

                kn = __webpack_require__(/*! Knoin/Knoin */ 5),
                AbstractView = __webpack_require__(/*! Knoin/AbstractView */ 11),
                AttachmentModel = __webpack_require__(/*! Model/Attachment */ 86)
  ;

        function MyModalViewB()
        {
           ...some observables...

        this.doSearch = Utils.createCommand(this, function() 
        {
           MyModelViewB.findUsers(userId);
        }

        kn.constructorEnd(this);
        }

        MyModelViewB.findUsers = function (userId)
        {
             //here I'm retriewing rows 
             //and I need I need to update rows from MyModalViewA
        }


    module.exports = MyModelViewB;

    }());

然后基于答案在Knockout中链接/同步视图模型的最佳方法是什么?我尝试使用PubSubMyModelViewA更新this.rows= ko.observableArray([]);.

Then based on an answer from Whats the best way of linking/synchronising view models in Knockout? I have tried to use PubSub to update this.rows= ko.observableArray([]); from MyModelViewA.

为此,我在MyModelViewA构造函数变量中添加了var postbox = ko.observable();.然后在MyModelViewA中我添加了

For that I have added var postbox = ko.observable(); to MyModelViewA constructor variables. Then in MyModelViewA I have added

   postbox.subscribe(function(newValue) {
        this.rows.push(newValue);
    }, this);

然后在MyModelViewB中我添加了

this.results = ko.observableArray([]);
this.results.subscribe(function(newValue) {
    postbox.notifySubscribers(newValue);
});

但是当我要在MyModelViewB中对newValue进行硬编码时,两个视图都没有得到newValue还是MyModelViewB都没有更新MyModelViewA this.rows可见.

But both views doesn't get what newValue is neither MyModelViewB is not updating MyModelViewA this.rows observable when I will hardcode newValue in MyModelViewB.

到那时,我不确定是否能从上面提到的链接中得到正确答案才能使它正常工作.

At that point I'm not sure if I have got correctly answer from mentioned link above to have get it to work.

编辑

我已经在模块捆绑代码的顶部添加了

I have added to top of my modules bundle code

var postbox = new ko.subscribable();

如下代码

(function($) { $(function() {
    window.postbox = new ko.subscribable();
    });
});

在尝试声明可订阅时抛出错误

was throwing error when trying to declare subscribable

无法读取未定义的属性"subscribe"

Cannot read property 'subscribe' of undefined

然后在MyModalViewA模块中添加了来自PFX答案的简化版本:

then in the module for MyModalViewA added simplified version from PFX answer:

    postbox.subscribe(function(newValue) {
            self.myTest(newValue);

            console.log('New value: ' + newValue);
        }, null, "NewRowAvailable"
    );

并在MyModelViewB.findUsers下的MyModalViewB模块中添加了

var newRow = "testing123";
postbox.notifySubscribers(newRow, "NewRowAvailable");

当我调试该代码时,它表明postbox被定义为Object {NewValueAvailable: },但是notifySubscribers并未更新可订阅.

When I will debug that code it shows that postbox was defined as Object {NewValueAvailable: } but notifySubscribers wasn't updating subscribable.

有什么想法吗?

推荐答案

确保postbox实例是一个,并且两个视图模型之间共享同一实例,并且notifySubscriberssubcribe方法遵循签名在下面.

Make sure that the postboxinstance is one and the same instance being shared between both viewmodels and that the notifySubscribersand subcribe methods follow the signatures below.

notifySubscribers(eventData, eventName); 

subscribe(function(eventData) { ... }, null, eventName);

下面找到了您要实现的目标的简化版本.
这里仅传递了1个搜索结果,但也可能会通过例如来更多.数组.

Below you find a simplified version of what you are trying to achieve.
Here only 1 search result is being passed, but it might also be more via eg. an array.

var postbox = ko.observable();

function MyModalViewA()
{
    var _self = this;
    _self.rows = ko.observableArray([
        { label: "foo" },
        { label: "bar" }    
        ]);
    
    postbox.subscribe(function(newValue) {         
          _self.rows.push(newValue);
      }, null, "PFX.NewRowAvailable"
      );
};

function MyModalViewB()
{
    var _self = this;
    
    _self.search = function() {
    
        var newRow = { "label" : "baz" };
        postbox.notifySubscribers(newRow, "PFX.NewRowAvailable");      
    };
};

var vma = new MyModalViewA();
ko.applyBindings(vma, $("#vma").get(0));

var vmb = new MyModalViewB();
ko.applyBindings(vmb, $("#vmb").get(0));

<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.4.2/knockout-min.js"></script>

<div id="vma">
    <h3>ViewModel A</h3>
    <ol data-bind="foreach: rows">
        <li data-bind="text: label"></li>
    </ol>
</div>

<hr />

<div id="vmb">    
    <h3>ViewModel B</h3>
    <button data-bind="click: search">search</button>
</div>

这篇关于KnockoutJS和PubSub更新视图之间的可观察数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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