调用applyBindings后,Observable会丢失值

时间:2014-10-13 04:16:43

标签: knockout.js

我正在研究这个fiddle试图找出一个我没有在select元素上设置的值的问题,现在我在jsfiddle中遇到了无意义的行为。我不知道这个问题是否是我的根本问题,或者这是否是jsfiddle中的错误。

首先,我使用我的视图模型继承:Using Super Constructors Is Critical In Prototypal Inheritance In Javascript 。也许这篇文章让我走上了错误的道路,我不知道。底线是我需要继承。

第二个问题是,在调用ko.applyBindings之后,我的observable只是失去了它的值(变为undefined),然后没有将其设置为1

enter image description here

function userAddressModelBase(data) {
    var self = this;
    self.states = ko.observableArray(data.states);
}

userAddressModel.prototype = new userAddressModelBase({});
userAddressModel.constructor = userAddressModel;

function userAddressModel(data) {
    var self = this;

    userAddressModelBase.call(self, data);

    self.sampleText = ko.observable("i'm here");

    console.log("data.selectedStateId is: " + data.selectedStateId);
    self.selectedStateId = ko.observable(data.selectedStateId);
    console.log("self.selectedStateId is: " + self.selectedStateId());

    self.getStates = function () {
        console.log("getStates running...");
        window.setTimeout(function () {
            console.log("getStates callback...");
            self.states([new stateModel({
                id: 1,
                name: "New York"
            }), new stateModel({
                id: 2,
                name: "Texas"
            }), new stateModel({
                id: 3,
                name: "California"
            }), new stateModel({
                id: 4,
                name: "Ohio"
            })]);
            console.log(ko.toJS(self));
            console.log("getStates callback self.selectedStateId is: " + self.selectedStateId());
        }, 1000);
    };

    //console.log("self.selectedStateId is: " + self.selectedStateId());
    //self.getStates();
    //console.log("self.selectedStateId is: " + self.selectedStateId());
}

function stateModel(data) {
    var self = this;
    self.id = ko.observable(data.id);
    self.name = ko.observable(data.name);
}

var model = new userAddressModel({ selectedStateId: 3 });

console.log(ko.toJS(model));
console.log("before applyBindings model.selectedStateId is: " + model.selectedStateId());
console.log("appling bindings...");
ko.applyBindings(model); // selectedStateId is now undefined!!!
console.log("appling bindings finished.");
console.log(ko.toJS(model));

console.log("after applyBindings model.selectedStateId is: " + model.selectedStateId());
model.getStates(); // selectedStateId is now 1 after this finishes!!!

1 个答案:

答案 0 :(得分:3)

是什么让您认为您的selectedStateId应该有价值?当然你最初设置一个值但是当一切都有机会加载和绑定时,它并不意味着它必须保持这个值。

该observable与空select下拉列表的值绑定。没有可用的值,还应该选择其他什么?只有在稍后你用一些值填充选择,所以现在你有一个值。

如果要保留该值,则需要确保在应用绑定或设置值时它不为空。