通过敲除中的点击绑定通过ajax请求更新视图模型

时间:2014-02-04 05:53:11

标签: jquery ajax knockout.js

我首先使用样本数据绑定了一个视图模型,绑定工作正常。

这是小提琴 http://jsfiddle.net/46LXU/

但是如果我使用点击绑定从服务器获取相同的数据,我会得到数据,但我无法使用它来加载它来查看模型。

<ul>
<li><a href="#" data-bind="click: function(data) { selectionChanged( 1 ) }">Sample Data 1</a></li>
<li><a href="#" data-bind="click: function(data) { selectionChanged( 2 ) }">Sample Data 2</a></li>
<li><a href="#" data-bind="click: function(data) { selectionChanged( 3 ) }">Sample Data 3</a></li>
</ul>

上面的每次点击都会通过以下jQuery Post从服务器加载新数据。

my.vm.selectionChanged = function (){
 //This loads new data from server
 jQuery.post(
      MyAjax.ajaxurl,
      {
          action : 'rcv_getpost',
          cvid : 2,
      },
      function( response ) {
           return {
             data: response 
            };
       }
    //Response now have the new data. How to load the data and to update it with view? 
    );      

my.vm.load();
}

我的实际视图模型

jQuery(document).ready(function ($) {


var my = { }; //my namespace

my.sampleData = (function (my) {    

    var dataary = {
  "sections": [
    {
      "section_name": "Qualifications",
      "data": "Sample Data",
      "key": "qual"
    },
    {
      "section_name": "Interests",
      "data": "These are my interests",
      "key": "int"
    },
    {
      "section_name": "Referance",
      "data": "This Is my referance",
      "key": "ref"
    }
  ]
};
     return {
             data: dataary
            };
})(my);

    // Product construction
    var Section = function () {
        this.section_name = ko.observable();
        this.data = ko.observable();
        this.key = ko.observable();
        this.prevent = ko.observable();
    };


    my.vm = {
        // observable array of sections
        sections: ko.observableArray([]),
        // loading the observable array with sample data
        load: function () {
            console.log(my.sampleData.data.sections);
            $.each(my.sampleData.data.sections, function (i, p) {
                    my.vm.sections.push(new Section()
                        .section_name(p.section_name)
                        .data(p.data)
                        .key(i)
                    )
            });
        }

    }; // End of My.VM


   my.vm.load();
   ko.applyBindings(my.vm);




});

1 个答案:

答案 0 :(得分:1)

在您的点击处理程序中:

  function( response ) {
       my.vm.load({
         data: response 
        });
   }

并删除对load()的其他调用。请记住,AJAX操作是异步;他们的回调不能返回值。

在你的虚拟机中:

    load: function (data) {
        console.log(data);
        my.vm.sections([]); // assuming you want to replace your sample data rather than append to it
        $.each(data.sections, function (i, p) {

最后:

my.vm.load(my.sampleData);
ko.applyBindings(my.vm);