KnockoutJS-从另一个模型视图可观察到的更新 [英] KnockoutJS - update observable from another modelview

查看:87
本文介绍了KnockoutJS-从另一个模型视图可观察到的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的ComposePopupView()模型视图,其中包含可观察的

I have an existing ComposePopupView() modelview which contains observable

this.attachments = ko.observableArray([]);

和下面的方法

ComposePopupView.prototype.addDropboxAttachment = function (oDropboxFile)
{
    var
        oAttachment = null,
        iAttachmentSizeLimit = Utils.pInt(Settings.settingsGet('AttachmentLimit')),
        mSize = oDropboxFile['bytes']
    ;

    oAttachment = new ComposeAttachmentModel(
        oDropboxFile['link'], oDropboxFile['name'], mSize
    );

    oAttachment.fromMessage = false;
    oAttachment.cancel = this.cancelAttachmentHelper(oDropboxFile['link']);
    oAttachment.waiting(false).uploading(true).complete(false);

    this.attachments.push(oAttachment);

    this.attachmentsPlace(true);

    if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
    {
        oAttachment.uploading(false).complete(true);
        oAttachment.error(Translator.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
        return false;
    }

    Remote.composeUploadExternals(function (sResult, oData) {

        var bResult = false;
        oAttachment.uploading(false).complete(true);

        if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
        {
            if (oData.Result[oAttachment.id])
            {
                bResult = true;
                oAttachment.tempName(oData.Result[oAttachment.id]);
            }
        }

        if (!bResult)
        {
            oAttachment.error(Translator.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded));
        }

    }, [oDropboxFile['link']]);

    return true;
};

然后我创建了另一个名为UsersDocumentsPopupView()的模型视图,在其中我以上述方式访问上述方法

Then I have created my other modelview called UsersDocumentsPopupView() where I'm accessing above method as

DropBox = __webpack_require__(/*! View/Popup/Compose */ 31)
....
DropBox.prototype.addDropboxAttachment(aFiles[0]);

但是会引发错误

无法读取未定义的属性附件"

Cannot read property 'attachments' of undefined

然后我决定添加可观察的

Then I have decided to add observable

this.attachments = ko.observableArray([]);

到我的模型视图,然后又累了

to my modelview and then tired to do

this.attachment.push(oAttachment);

其中oAttachment是从aFiles数组中获取的对象,但仍然出现相同的错误.

where oAttachment is an object taken from aFiles array but still I'm getting the same error.

我的问题是,如何甚至可以从一个执行另一个Modelview的modelview更新可观察的attachments?

My question is how or even if can I update observable attachments from one modelview executing another modelview?

PS. 当我在ComposePopupView()中执行以下代码时,效果很好

PS. When I will do code below in the ComposePopupView() it works fine

var aFiles = [JSON.parse('{"isDir": false,  "name": "koala.jpg", "bytes": 780831,"link": "http://localhost/data/koala.jpg","id": "id:UxmT1S5QcFAAAAAAAAAACw"}')];

if (aFiles && aFiles[0] && aFiles[0]['link'])
{
  console.log("Test");
  self.addDropboxAttachment(aFiles[0]);
}

那么在这种情况下,如何将数据aFilesUsersDocumentsPopupView()传递到ComposePopupView()模型视图?

So in this case how can I pass data aFiles from the UsersDocumentsPopupView() to ComposePopupView() modelview?

推荐答案

我最终使用了Knockout的发布/订阅功能.

I have ended up to using Knockout's pub/sub functionality.

下面的基本示例:

var postbox = ko.observable();

function MyModalViewA()
{
    var _self = this;
    var test = new Array();
    _self.rows = ko.observableArray([]);

    postbox.subscribe(function(newValue) {         
          _self.rows.push(newValue);
          //test = test.concat(newValue);
          console.log("Rows " + JSON.stringify(test));
      }, null, "NewRowAvailable"
      );
};

function MyModalViewB()
{
    var _self = this;

    _self.search = function() {

        var newRow = JSON.parse('{ "label" : "abc" }');
        postbox.notifySubscribers(newRow, "NewRowAvailable");      
    };
};

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

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

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

The first view model subscribes to a specific topic and the second view model notifies through the postbox on that topic. There is 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/xpvt214o/708647/

此外,邮箱可能只是一个ko.subscribable()(包含在ko.observable函数中).

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

这篇关于KnockoutJS-从另一个模型视图可观察到的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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