从JSON更新Knockout.js Observable [英] Update Knockout.js Observable from JSON

查看:76
本文介绍了从JSON更新Knockout.js Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个网格并通过JSON用更多记录更新它.在这个简单的示例中,我能够实现所需的功能,但是我只能更新/推送一条JSON记录.我想能够通过JSON添加多个记录吗?我怎样才能做到这一点?我以为我可能必须创建某种for循环并将每个JSON结果推送到可观察到的位置,但是我希望敲除可能有更好的方法通过JSON更新/解析?

I'm attempt to establish a grid and update it with more records via JSON. In this simple example I am able to achieve the required functionality but I can only update / push one JSON record. I would like to be able to add multiple records via JSON? How could I achieve this? I assumed I might have to create some sort of for loop and push each JSON result to the observable but I was hoping that knockout might have a better way of updating / parsing via JSON?

这里是我到目前为止所取得成就的副本: http://jsfiddle.net/sparkhill/crSbt/

Heres a copy of what I have achieved so far: http://jsfiddle.net/sparkhill/crSbt/

     function Users(user_id, password) {
    this.user_id = ko.observable();
    this.password = ko.observable();
}

var viewModel = {

    users: ko.observableArray([]),


    addUser: function () {
        this.users.push({

            user_id: "",
            password: ""
        });
    },

    addJSON: function () {


        //Works Fine
        var JSONdataFromServer
        ='{"user_id":"frances","password":"password"}';

        //More than one result - wont map - Would Ideally like to map lots of records at one time
//var JSONdataFromServer ='{"user_id":"frances","password":"password"}, {"user_id":"frances","password":"password"}';

        var dataFromServer = ko.utils.parseJson(JSONdataFromServer);


        this.users.push(dataFromServer);

         //Tried
        //this.users.push(JSON.parse(JSONdataFromServer));


    }

};

viewModel.users();
ko.applyBindings(viewModel);

    </script> 

更新此功能似乎可行,但我想知道它们是否是更有效的方法?

addJSON: function () {

        //Works Fine
        var JSONdataFromServer
        ='[{"user_id":"frances","password":"password"},{"user_id":"timmy","password":"password"}]';

        var results = JSON.parse(JSONdataFromServer);

        var i = results.length;

        for(var i = 0; i < results.length; i++){

            this.users.push(results[i]);
      };   

推荐答案

以下是您可以通过以下三种方法实现此目的的方法:

Here are 3 ways you could do this ... found in this fiddle: http://jsfiddle.net/johnpapa/nfnbD/

1)使用ko.utils.arrayPushAll函数 2)使用自己的逻辑 3)在observableArray上编写自己的函数

1) Use the ko.utils.arrayPushAll function 2) use your own logic 3) Write your own function on observableArray

详细信息...

1)如果使用ko.utils.arrayPushAll函数,那么您还需要调用valueHasMutated,因为数组实际上会被自身覆盖.除非您告诉它已更改,否则可观察性不会触发.这是您可以执行的操作:

1) If you use the ko.utils.arrayPushAll function you will need to call valueHasMutated too, because the array effectively gets overwritten with itself. The observability does not fire off unles you tell it that it changed. Here is how you could do that:

ko.utils.arrayPushAll(this.users(), dataFromServer);
this.users.valueHasMutated();

2)第二种选择是编写自己的循环逻辑,基本上使用与arrayPushAll函数相同的代码,像这样.

2) The second option is to write your own loop logic, essentially using the same code as the arrayPushAll function like this.

for (var i = 0, j = dataFromServer.length; i < j; i++)
this.users.push(dataFromServer[i]);

3)在observableArray上创建自己的函数,如下所示:

3) Create a function of your own on the observableArray, like this:

ko.observableArray.fn.pushAll = function(valuesToPush) {
        var items = this;
        for (var i = 0, j = valuesToPush.length; i < j; i++){
            items.push(valuesToPush[i]);
        }
        return items;
};

尽管上面的代码将在每次添加项目时进行通知.因此,最好将它们全部添加,然后通知.这样会更有效率.像这样:

Though this code above will notify every time an item is added. So it might be better to add them all, then notify. This would be more efficient. Like this:

ko.observableArray.fn.pushAll = function(valuesToPush) {
    var underlyingArray = this();
    this.valueWillMutate();
    ko.utils.arrayPushAll(underlyingArray, valuesToPush);
    this.valueHasMutated();
    return this;
};

然后这样称呼它:

this.users.pushAll(dataFromServer);

这篇关于从JSON更新Knockout.js Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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