繁体   English   中英

Knockout.js:手动触发计算

[英]Knockout.js : manually trigger computed

我在页面上有一个网格和一个选择控件。 选择任何选择值都会触发网格更新。 使用computed完成更新。 我可以手动触发网格更新,例如,在将新值添加到网格时的情况吗?

 function vm(){
    var self = this;

    self.items = ko.observableArray([]);
    self.chosen_category = ko.observable("");

    self.pager = {
        page_namber : ko.observable(1),
        page_size : ko.observable(10)
    };

     self.sort = {
       field : ko.observable('name'),
       dist : ko.observable('asc')
     };
     // etc. 

     self.fetch = ko.computed(function(){
        $.ajax({
               url: '/api/items/',
               type: 'GET',
               data: ko.toJSON(self),
               contentType: 'application/json',
               success: self.items
          });
     }, self);


      self.add_item = function() {
        //here I want to update the grid
        self.fetch(); // not work
      };
 }

当然我可以把它移到一个单独的功能,但我正在寻找一个更清洁的解决方案。 谢谢!

工作版:

          function vm() {
            var self = this;

            self.items = ko.observableArray([]);
            self.chosen_category = ko.observable("test");

            self.pager = {
                page: ko.observable(1),
                size: ko.observable(10)
            };

            self.sort = {
                field: ko.observable('name'),
                dist: ko.observable('asc')
            };

            self.fetch = function () {
                var data = {
                    category: self.chosen_category(),
                    pager: ko.toJS(self.pager),
                    sort: ko.toJS(self.sort)
                };

                $.ajax({
                    url: '/api/items/',
                    type: 'POST',
                    data: ko.toJSON(data),
                    contentType: 'application/json',
                    success: self.items
                });
            };

            self._auto_update = ko.computed(self.fetch).extend({ throttle: 1 }); ;

            self.add_item = function () {
                self.fetch();
            };
        }

最好使用subscription而不是computed来执行此操作。 在这种情况下,您可以定义用于订阅和手动调用的提取功能:

function vm(){
  var self = this;

  self.items = ko.observableArray([]);
  self.chosen_category = ko.observable("");

  self.fetch = function(){   
    $.get('/api/items/' + self.chosen_category(), self.items);
  };

  self.chosen_category.subscribe(self.fetch);


  self.add_item = function() {
   //here I want to update the grid
   self.fetch(); 
  };
}

你也可以用计算机做同样的事情:

function vm(){
  var self = this;

  self.items = ko.observableArray([]);
  self.chosen_category = ko.observable("");

  self.fetch = function(){   
    $.get('/api/items/' + self.chosen_category(), self.items);
  };

  self.doStaff = ko.computed(self.fetch);


  self.add_item = function() {
   //here I want to update the grid
   self.fetch(); 
  };
}

暂无
暂无

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

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