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

查看:26
本文介绍了从 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]);
      };   

推荐答案

这里有 3 种方法可以做到这一点......在这个小提琴中找到:http://jsfiddle.net/johnpapa/nfnbD/

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天全站免登陆