【问题标题】:KnockoutJS Accessing an array of objects in a separate classKnockoutJS 在单独的类中访问对象数组
【发布时间】:2012-04-08 09:10:03
【问题描述】:

所以我有 2 个课程,用户和健康读数。我制作了一个用户对象数组,里面有一个读数数组。我只想访问读数数组中的日期和重量,我已经尝试了很长时间来解决这个问题!请帮助这个简单的问题让我发疯!

// Class to represent a row in the seat reservations grid
function Reading(theDate,theWeight)
{

    self.theDate=ko.observable(theDate);
    self.theWeight=ko.observable(theWeight);
}

function User(name,weight,date) {
    var self = this;
    self.name = name;
    self.date = date;
    self.weight = ko.observable(weight);
     self.theReadings = ko.observableArray([
        new Reading(12,13)
    ]);

}
    // Editable data
      self.users = ko.observableArray([
        new User("George",1,2012),
        new User("Bindu",2,2012)
    ]);
    /this alerts an object but i dont know how to access the weight/date variable
    alert(self.users()[0].theReadings()[0]);

    self.readings = ko.observableArray([
        new Reading(12,13)

【问题讨论】:

    标签: arrays object knockout.js


    【解决方案1】:
    alert(self.users()[0].theReadings()[0].theWeight();
    

    我建议删除“thes”。这是一种不常见的风格。

    【讨论】:

    • 我尝试添加 .theWeight() 但它不起作用。它只是破坏了一切。
    【解决方案2】:

    只是错过了一些关于这个的东西。

    给你。

    http://jsfiddle.net/EN7y4/3/

    即。您在函数 Reading 中有“self.theWeight”而不是“this”。...

    编码愉快!

    【讨论】:

    • 还有一件事。 self 在后面的代码(可编辑数据下方)中起作用的唯一原因是它引用了window.self。这有点令人困惑。
    • 哇,非常感谢!我知道这是我做错的小事。
    • self,正如马修所说,不是你应该玩的对象。将全局对象保存在命名空间(var myapplication 或类似的东西)或 DOM(jquery.data() 对象)中会很聪明
    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 2016-08-24
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    相关资源
    最近更新 更多