【问题标题】:Transform method not working in knockout js postbox转换方法在淘汰赛 js 邮箱中不起作用
【发布时间】:2019-01-04 02:40:37
【问题描述】:

我正在使用淘汰赛邮箱插件来遵循淘汰赛中的 pub sub 模式。我能够在组件之间接收和发送数据,但问题是我无法使用转换功能。

下面是代码和小提琴链接..有人可以告诉我我在这里做错了什么

  <div id="container1">
        First View Model:
      <input type="text" data-bind="value: data1">      

    </div>
    <br/>
     <div id="container2">
     Second View Model:
       <span data-bind="text: data2"></span><br/>
        <span data-bind="text: newData"></span>
    </div> 

这是我的模型

function Container1ViewModel()
{
    var self = this;
    self.data1 = ko.observable(false).publishOn("showDiv"); 

} 
function Container2ViewModel() {
    var self = this;
    this.data2 = ko.observable().subscribeTo("showDiv", true,transform);
    this.newData = ko.observable('45');
    var transform = function(newValue) {
    newData(newValue);
    return 123;
};

}


var container1VM;
var container2VM;

        container1VM = new Container1ViewModel();
        ko.applyBindings(container1VM, document.getElementById("container1"));

        container2VM = new Container2ViewModel();
        ko.applyBindings(container2VM, document.getElementById("container2"));

这里是小提琴链接Fiddle

我在这里寻找的是使用转换函数通过订阅者可观察对象设置另一个可观察对象的值,以便我可以转换数据并分配它。

谢谢

【问题讨论】:

  • 是否需要使用邮箱?为什么不只通过淘汰订阅来做到这一点?

标签: knockout.js knockout-3.0 knockout-postbox


【解决方案1】:

您忘记了对 self 的一些引用,并且还放错了第二个 ViewModel 中 transform 函数的定义。

function Container2ViewModel() {
    var self = this;

    var transform = function(newValue) {
        self.newData(newValue);

        // this will ALWAYS be the value passed to self.data2
        return 123;
    };

    self.newData = ko.observable('47');
    self.data2 = ko.observable().subscribeTo("showDiv", true, transform);
}

我用代码的工作版本更新了小提琴:http://jsfiddle.net/0454h205/304/

请注意,在转换中始终返回“123”使得 data2 可观察对象始终为“123”。

【讨论】:

    猜你喜欢
    • 2016-08-21
    • 2012-01-30
    • 2013-05-27
    • 2014-11-12
    • 2018-05-21
    • 2013-01-30
    • 1970-01-01
    • 2014-05-10
    • 2014-10-28
    相关资源
    最近更新 更多