Knockout.js: manually triggered

I have a grid and a control on the page. Select any grid update trigger selection value. This update is performed using calculated ones. Can I manually activate the grid to update, say, in a situation where a new value is added to the grid?

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 }; } 

Of course, I can move it to a separate function, but I'm looking for a cleaner solution. Thanks!

working version:

  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(); }; } 
+6
source share
1 answer

It is better to do this using subscription instead of computed . In this case, you can define a fetch function to use for both subscription and manual call:

 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(); }; } 

You can also do the same with the calculated ones:

 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(); }; } 
+9
source

All Articles