淘汰javascript foreach绑定 [英] knockout javascript foreach binding

查看:80
本文介绍了淘汰javascript foreach绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许用户创建一个转换并向此转换对象添加一个类别数组。我试图使用knockout的foreach绑定到类别数组,并让用户向转换添加新类别。我创建了一个jsfiddle来说明我在这里要解释的内容。

http ://jsfiddle.net/msell/ueNg7/16/

I'm trying to allow a user to create a casting and add an array of categories to this casting object. I was trying to use knockout's foreach binding to the array of categories and let users add new categories to the casting. I have created a jsfiddle to illustrate what I'm trying to explain here.
http://jsfiddle.net/msell/ueNg7/16/

当用户修改一个转换时,JSON对象会正确构建,但我不能说获取要显示的铸件列表。

The JSON object gets built up correctly as a user modifies a casting, but I cant quite get the list of castings to display.

推荐答案

您有几个问题:

在Knockout 2.0之前,未添加 foreach 绑定。

The foreach binding was not added until Knockout 2.0.

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

You need to modify your categories property to be a ko.observableArray(), instead of just an empty array. Otherwise Knockout will not be able to observe when you push to it, and the remove method will not exist.

从事件处理程序,将被错误地设置。您可以通过各种方式解决此问题,在Knockout文档中详细讨论,但一个简单修复是将引用更改为 viewModel 而不是

When called from event handlers, this will be set incorrectly. You can fix this in various ways, discussed in length in the Knockout documentation, but one easy fix is to change the references to viewModel instead of to this.

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

To fix all these, you should upgrade to Knockout 2.0, and change your view model declaration to be

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/

Here is a corrected JSFiddle: http://jsfiddle.net/ueNg7/19/

这篇关于淘汰javascript foreach绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆