Applying knockout extenders after mapping

流过昼夜 提交于 2019-12-23 08:04:19

问题


I'm having a problem with adding a knockout extender to observables after they have been created. In the following example the extender is run on foo every time the value changes as expected but only once, when first called, for bar.

var viewModel = function(){
    var self = this;

    self.foo = ko.observable(1).extend({ numeric: 1 });

    self.bar = ko.observable(1);

    self.bar.extend({ numeric: 1 });
};

Essentially I am mapping a large JSON object and would like to add extenders after the mapping has occurred to some of the properties. Is there a simple way to do this?

Below is a jsfiddle showing the problem:

http://jsfiddle.net/LgxTn/


回答1:


The problem you have is that the extender is creating a new observable (based on the observable it's extending). And that new observable is not being used in your second call to extend.

To fix this (without changing the code of the extender) you can assign the response from calling extend into the same property it's called.

In other words, add self.bar = in front of your last line in order to have this:

self.bar = self.bar.extend({ numeric: 1 });


来源:https://stackoverflow.com/questions/16986262/applying-knockout-extenders-after-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!