javascript Knockoutjs 绑定对象问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19699693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:31:20  来源:igfitidea点击:

Knockoutjs binding objects issue

c#javascriptjqueryasp.net-mvc-4knockout.js

提问by IDeveloper

I'm studying knockoutjs and having some issues. I have ASP.NET MVC page with a method returning list of three Car objects is JSON. I than map it to selectin HTML view and I want to display cost of a selected car on selection change. The problem is that a name of a car is visible while a price is not ('A Mercedes-Benz costs .'). What it could be? Thanks in advance! Controller:

我正在研究knockoutjs 并且遇到了一些问题。我有一个 ASP.NET MVC 页面,其中一个方法返回三个 Car 对象的列表是 JSON。我将它映射到selectHTML 视图中,并且我想在选择更改时显示所选汽车的成本。问题是汽车的名称是可见的,而价格则不可见(“梅赛德斯-奔驰成本。”)。它可能是什么?提前致谢!控制器:

public class Car
{
    public string Make { get; set; }
    public decimal Price { get; set; }
}
public JsonResult GetCars()
{
    List<Car> cars = new List<Car>();
    cars.Add(new Car { Make = "Mercedes-Benz", Price = 103000 });
    cars.Add(new Car { Make = "Toyota", Price = 37000 });
    cars.Add(new Car { Make = "Huyndai", Price = 17000 });
    return Json(cars, JsonRequestBehavior.AllowGet);
}

And View with Javascript code:

并使用 Javascript 代码查看:

<head>
    <script type="text/javascript" src="~/Scripts/jquery-2.0.3.min.js"></script>
    <script type="text/javascript" src="~/Scripts/knockout-3.0.0.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            function Car(data) {
                this.Make = ko.observable(data.Make);
                this.Price = ko.observable(data.Price);
            }

            function CarsViewModel() {
                var self = this;
                //Data
                self.someOptions = ko.observableArray([]);
                self.myOption = ko.observable();

                //Operations
                self.initData = function () {
                    $.get('/Home/GetCars', function (data) {
                        var mappedCars = $.map(data, function (item) { return new Car(item) });
                        self.someOptions(mappedCars);
                    });
                }
            }

            ko.applyBindings(new CarsViewModel());
        });

    </script>
</head>
<body>
    <div>
        <button data-bind="click: initData">Load data</button>
        <h4>Preview</h4>
        <p>
            <select data-bind="options: someOptions, optionsText: 'Make', value: myOption"></select><br />
            A <span data-bind="text: myOption().Make"></span> costs <span data-bind="text: myOption().Price"></span>.
        </p>
    </div>
</body>

回答by nemesv

If you check your browser's JavaScript console you should see the following error:

如果您检查浏览器的 JavaScript 控制台,您应该看到以下错误:

Uncaught TypeError: Unable to process binding "text: function (){return myOption().Make }" Message: Cannot read property 'Make' of undefined

未捕获的类型错误:无法处理绑定“text: function (){return myOption().Make }” 消息:无法读取未定义的属性“Make”

You get this error because when your page is loaded your myOptionis empty so it does not have a Makeand Priceproperties. So KO cannot execute the binding data-bind="text: myOption().Make"and it stops with the processing of the further bindings.

您收到此错误是因为当您的页面加载时,您的页面是myOption空的,因此它没有MakePrice属性。因此 KO 无法执行绑定data-bind="text: myOption().Make",它会随着进一步绑定的处理而停止。

After calling initDatanow you have something in myOptionbut still all the bindings after the data-bind="text: myOption().Make"won't work anymore.

initData现在调用后,您有一些东西,myOption但仍然data-bind="text: myOption().Make"无法再使用之后的所有绑定。

To solve this there are multiple ways like:

要解决这个问题,有多种方法,例如:

  • using a default value in myOption
  • check for null in your bindings with data-bind="text: myOption() && myOption().Make"
  • or use the withbinding
  • 在 myOption 中使用默认值
  • 检查您的绑定中的空值 data-bind="text: myOption() && myOption().Make"
  • 或使用with绑定

Here is an example for the withbinding:

这是with绑定的示例:

<!-- ko with: myOption -->
   A <span data-bind="text: Make"></span> 
   costs <span data-bind="text: Price"></span>.
<!-- /ko -->

Demo JSFiddle.

演示JSFiddle