【问题标题】:knockout.js how to add and replace binding instance?knockout.js 如何添加和替换绑定实例?
【发布时间】:2011-07-19 04:11:45
【问题描述】:

我有以下 knockout.js 代码

我有以下内容:

var itemLine = function() {
    this.itemId = ko.observable();
    this.itemType = ko.observable();
    ///this.otherFields = = ko.observable();....
};

var itemSet = function () {
    this.items = ko.observableArray(_.map(initialData, function (item) {
        var newItem = new itemLine();
        newItem.itemId(item.itemId);
        newItem.itemType(item.itemType);
        return newItem;
    }));

    this.current = new itemLine();

    // works, but it req duplication of all my fields
    this.add = function () {
        var newItem = new itemLine();
        newItem.itemId(this.current.itemId());
        newItem.itemType(this.current.itemType());

        this.items.push(newItem);
        this.current.itemerId("");
        this.current.itemType("");
    };

    // doesn't work
     this.add = function () {
        this.items.push(this.current);
        this.current = new interviewLine(); // bindings are lost
    };

第二个 add 实现有什么问题?这样做的正确方法是什么?

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    目前,在您的第二次添加中,您实际上并没有更新 observable,只是用新的替换它们。

    我要做的是使 this.current 成为可观察的。然后在第二个版本的 add 中,您将设置 current 为新值,就像设置任何 observable 一样。

    因此,在您的 itemSet 构造函数中,您可以像这样初始化 this.current:

    this.current = ko.observable(new itemLine());
    

    然后,在您的第二个添加函数中,将 this.current 设置为:

    this.current(new interviewLine());
    

    类似这样的:http://jsfiddle.net/rniemeyer/j72NU/

    这是否接近您想要做的事情?

    【讨论】:

    • 谢谢,这就是我想要做的。是否可以将“当前”编辑器作为模板?
    • 是的,应该是这样的:jsfiddle.net/rniemeyer/KSPGA。绑定被实现为dependentObservables,因此在绑定中访问 c​​urrent() 将触发它们在当前更改的任何时候重新运行,它应该会给你想要的结果。
    猜你喜欢
    • 1970-01-01
    • 2017-09-07
    • 2013-11-07
    • 2017-11-02
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多