【问题标题】:Knockout JS - observable array needs to be populated from the detail objectKnockout JS - 需要从详细对象中填充可观察数组
【发布时间】:2012-03-20 13:12:30
【问题描述】:

这是小提琴 http://jsfiddle.net/srinivasanvee/yYEwJ/2/

我有一个列表,其中包含类别、产品、数量作为列, 我可以选择从下拉列表本身添加新类别(选择 --Add new-- 选项), 想要从类别订阅方法填充 categoryList observableArray(因为新添加的值必须应用于网格的所有行), 不知道怎么做,尝试了 $root.categoryList.push(name),但没有运气

或者我们有更好的方法来处理这种情况吗? 非常感谢您的帮助,在此先感谢。

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    $root 等变量仅在绑定中可用。

    完成这项工作的一种方法是将对您的根视图模型的引用传递给您的 cartLine 构造函数。

    您的 cartLine 最终会如下所示:

    var cartLine = function(data1, root) {
        this.category = ko.observable(data1.category);
        this.product = ko.observable(data1.product);
        this.quantity = ko.observable(data1.quantity);
    
        this.category.subscribe(function(newValue) {
            if (newValue == "--Add New--") {
                var name = prompt("Enter Table Name");
                if (name == null) {  
                    return false;
                }
                else {
                    root.categoryList.push(name);
                }
            }
        });
    };
    

    然后,您只需在创建新的 cartLine 时将 this 作为视图模型的第二个参数传入。示例:http://jsfiddle.net/rniemeyer/kzZSH/

    否则,您可以照原样创建您的 cartLine,并在获得对新行的引用后从您的 viewModel 订阅。

    【讨论】:

      猜你喜欢
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2014-06-22
      • 1970-01-01
      • 2019-06-02
      • 2016-04-25
      相关资源
      最近更新 更多