从可观察数组中获取对象 [英] Get object out of observable array

查看:129
本文介绍了从可观察数组中获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在此代码中m未定义":

Why is m "undefined" in this code:

currentViewModel = ko.mapping.fromJS(viewModel);
currentViewModel.getReport = function(reportId) {
    for(var i=0;i<currentViewModel.availableReports().length;i++) {
        if(currentViewModel.availableReports()[i].id == reportId) {
            var m = currentViewModel.availableReports()[i];
            return currentViewModel.availableReports()[i];
        }
    }
}

我将getReport()称为onclick事件,并且要将报告对象发送到视图(模式),我可以在availableReports上进行foreach操作,所有操作都在这里.当我运行调试器时,它会遍历数组并找到合适的数组.但是为什么我不能将其拉出阵列呢? "m"保持未定义状态,该函数返回未定义状态.

I call getReport() as an onclick event and I want to send the report object to a view (modal) I can do a foreach on the availableReports and it's all there. When I run through the debugger, it loops through the array and finds the right one. But why can't I pull it out of the array? "m" remains undefined the the function returns undefined.

我在这里想念什么?

这里有一个后续问题: knockout.js可以等待绑定直到onClick吗?

推荐答案

您只需要将if(currentViewModel.availableReports()[i].id ...更改为if(currentViewModel.availableReports()[i].id() ...,因为映射id之后将成为可观察的函数.

You just need to change if(currentViewModel.availableReports()[i].id ... to if(currentViewModel.availableReports()[i].id() ... because after mapping id will become an observable, i.e. function.

更新的代码:

currentViewModel = ko.mapping.fromJS(viewModel);
currentViewModel.getReport = function(reportId) {
    for (var i = 0; i < currentViewModel.availableReports().length; i++) {
        if (currentViewModel.availableReports()[i].id() == reportId) {
            var m = currentViewModel.availableReports()[i];
            return currentViewModel.availableReports()[i];
        }
    }
}

演示-小提琴.

这篇关于从可观察数组中获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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