【问题标题】:knockout javascript foreach binding淘汰 javascript foreach 绑定
【发布时间】:2012-04-24 14:02:32
【问题描述】:

我试图让用户创建一个演员表并向这个演员表对象添加一个类别数组。我试图使用淘汰赛的 foreach 绑定到类别数组,并让用户将新类别添加到铸件中。我创建了一个 jsfiddle 来说明我在这里要解释的内容。
http://jsfiddle.net/msell/ueNg7/16/

当用户修改演员表时,JSON 对象会正确构建,但我无法获得要显示的演员表列表。

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    你有几个问题:

    您正在使用 Knockout 1.2.1

    foreach 绑定直到 Knockout 2.0 才添加。

    您没有使用observableArray

    您需要将categories 属性修改为ko.observableArray(),而不仅仅是一个空数组。否则当你push 时,Knockout 将无法观察到它,remove 方法将不存在。

    您的this 绑定错误。

    从事件处理程序调用时,this 将被错误设置。您可以通过多种方式解决此问题,discussed in length in the Knockout documentation,但一个简单的解决方法是将引用更改为 viewModel 而不是 this


    要解决所有这些问题,您应该升级到 Knockout 2.0,并将您的视图模型声明更改为

    var viewModel = {
        name: ko.observable(''),
        description: ko.observable(''),
        categories: ko.observableArray(),
        categoryToAdd: ko.observable(''),
    
        removeCategory: function(category) {
            viewModel.categories.remove(category);
        },
    
        addCategory: function() {
            viewModel.categories.push(new Category(viewModel.categoryToAdd()));
            viewModel.categoryToAdd('');
        }
    };
    

    这是一个更正的 JSFiddle:http://jsfiddle.net/ueNg7/19/

    【讨论】:

    • 感谢您的详细回复!正是我想要的。
    【解决方案2】:

    你需要为你的数组使用 ko.observableArray 否则 Knockout 不会知道你什么时候改变你的数组并且不会更新,你也应该使用模板来代替,阅读这里http://knockoutjs.com/documentation/template-binding.html#note_2_using_the_foreach_option_with_a_named_template

    var viewModel = {
        name: ko.observable(''),
        description: ko.observable(''),
        categories: ko.observableArray([]),
        categoryToAdd: ko.observable(''),
        removeCategory: function(category) {
            this.categories.remove(category);
        },
    
        addCategory: function() {
    
            this.categories.push(new Category(this.categoryToAdd()));
            this.categoryToAdd('');
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      相关资源
      最近更新 更多