ko.mapping:使用订阅更新模型

时间:2013-04-25 17:11:49

标签: knockout.js knockout-mapping-plugin

ko.mapping更新我的模型时遇到错误,该模型有一些订阅。一旦订阅被删除,一切都像魅力一样。知道如何让它发挥作用吗?

考虑此示例(jsfiddle available) - 在ko.mapping.fromJS()中调用initModel()会触发错误:

var iniData = {
    FirstName: "foo",
    LastName: "bar"
};

var PersonModel = function() {
    this.FirstName = ko.observable("");
    this.LastName = ko.observable("");
    this.FullName = ko.observable("");

    // If you comment out subscribe() calls, everything works fine!
    this.FirstName.subscribe(this.updateFullName);    
    this.LastName.subscribe(this.updateFullName);


    // Update FullName only if it's empty
    this.updateFullName = function(){
            if (!this.FullName()) {
                this.FullName(
                    this.LastName() + 
                            this.FirstName() ? (
                                " " + this.FirstName()
                            ):''
                );
            }

        };
    this.initModel = function(){
        try {
        ko.mapping.fromJS(iniData, {}, this);
        }
        catch(err) {
            alert(err.message);
        }
    }
}

ko.applyBindings(new PersonModel());

2 个答案:

答案 0 :(得分:1)

updateFullName函数应该放在你正在进行的两个订阅之前,否则这个方法尚未为JavaScript解释器所知。像这样:

    var self = this;
    self.FirstName = ko.observable("");
    self.LastName = ko.observable("");
    self.FullName = ko.observable("");

    // Update FullName only if it's empty
    self.updateFullName = function(){
            if (!self.FullName()) {
                self.FullName(
                    self.LastName() + 
                            self.FirstName() ? (
                                " " + self.FirstName()
                            ):''
                );
            }

        };

    // If you comment out subscribe() calls, everything works fine!
    self.FirstName.subscribe(self.updateFullName);    
    self.LastName.subscribe(self.updateFullName);

另外,我认为在你的情况下你应该避免订阅并将FullName声明为计算的observable,这实际上是完美的情况。这是如何做到的:

self.FirstName = ko.observable("");
self.LastName = ko.observable("");
self.FullName = ko.computed(function() {
  return self.LastName() + (self.FirstName() ? " " + self.FirstName() : "");
};

每当FirstNameLastName中的某些内容发生变化时,计算出的FullName可观察量就会更新。


编辑:我检查了你的小提琴,另一个错误的是在updateFullName函数中,“this”指的是方法的上下文,而不是视图模型的上下文。这解释了为什么找不到fullName属性。查看更新后的fiddle

答案 1 :(得分:0)

计算的观察值在这里是否更有意义?或者fullName值是否必须可以自己编辑?

[编辑]哎呀,Jalayn更快;)