简体   繁体   English

如何从(init)JSON函数调用(ko.observableArray)?

[英]how can I call the (ko.observableArray) from (init) JSON function?

Well the title is confusing so I'll give you my code to understand my problem 好吧,标题令人困惑,所以我给你我的代码以理解我的问题

in knockout tutorials they use functions instead of JSON I mean like this: 在淘汰赛教程中,他们使用函数而不是JSON,我的意思是这样的:

data = [
  {
    id: 1,
    name: 'somehing'
  },{
    id: 2,
    name: 'somehing else'
  },
]

here is my problem 这是我的问题

var ViewModel = function () {
    var self = this;
    self.dataList = ko.observableArray(data);
    console.log(ViewModel.dataList);
};

while on other websites and most of tutorials and projects in github uses JSON 而在其他网站上以及github中的大多数教程和项目都使用JSON

var ViewModel = {
     dataList : ko.observableArray(data),
     init: function() {
      console.log(ViewModel.dataList);
      }
};

this line 这条线

     dataList : ko.observableArray(data),

when I try to call dataList it return this 当我尝试调用dataList时返回此

function d(){if(0<arguments.length)return d.Wa(c,arguments[0])&&(d.X(),c=arguments[0],d.W()),this;a.k.Ob(d);return c}

and If I try to get its value console will tell me that dataList is not defined 如果我尝试获取其值,控制台将告诉我未定义dataList

but if I pass data directly to dataList like this (Which is not observableArray anymore) it will give me the full objects values in console 但是如果我像这样将数据直接传递到dataList (不再是observableArray),它将在控制台中为我提供完整的对象值

     dataList : dataList,

the return value in console 控制台中的返回值

[Object, Object]

how can I call the ko.observableArray from init function? 如何从init函数调用ko.observableArray

I want to follow the tutorials on the web like this one but my issue is the same. 我想按照这样的方式在网上学习教程,但是我的问题是相同的。

http://opensoul.org/2011/06/23/live-search-with-knockoutjs/ http://opensoul.org/2011/06/23/live-search-with-knockoutjs/

Actually it's not only ko.observableArray arrays also I cannot call ko.observable objects 实际上,不仅是ko.observableArray数组,而且我不能调用ko.observable对象

when I try to call dataList it return this 当我尝试调用dataList时返回此

Your code doesn't call ViewModel.dataList , it just accesses it, which gives you the function (remember observables are functions). 您的代码不会调用 ViewModel.dataList ,而只是访问它,从而为您提供了函数(记住可观察对象是函数)。 To call it, add () : 调用它,添加()

console.log(ViewModel.dataList());
// Note ----------------------^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM