How to get ko.computed to work with observables inside an object

I have a pretty simple presentation model to store a data array and accept a string that I want to use to filter data.

I have a very simple inscription to make it like this:

<section class="task-list">
    <ul data-bind="foreach:filteredRecords">
        <li>
            <label>Task name:</label>
            <span data-bind="text:TaskName"></span>              
        </li>
    </ul>
</section>

and I created the model as follows:

var viewModel = {

    searchText : ko.observable(''),
    taskData : ko.observableArray([]),

    searchData : function () {

        // use ko.utils.arrayFilter to limit records by searchText()
        return this.taskData();
    },

    filterRecords: ko.computed(this.searchData, this).extend({ throttle: 500 }),
};

ko.applyBindings(viewModel, $('.task-list')[0]); 

I get

Uncaught Error: Pass a function that returns the value of the ko.computed 

moving the function back inside ko: is calculated as follows:

 filteredRecords: ko.computed(function () {
        return this.taskData();
    },this).extend({ throttle: 500 })

just giving me this error:

Uncaught TypeError: Object [object global] has no method 'taskData' 

So, I tried to define another property that should be used instead:

var viewModel = {

    _self : this,

    searchText : ko.observable(''),
    taskData : ko.observableArray([]),

    filteredRecords: ko.computed(function () {
        return this.taskData();
    },this).extend({ throttle: 500 })
};

but now it gives an error

Uncaught ReferenceError: _self is not defined 

Finally, I tried to do this:

var viewModel = {

    searchText : ko.observable(''),
    taskData : ko.observableArray([]),

    filteredRecords: ko.computed(function() {
        var me = this;
        return function () {
            return me.taskData();
        }
    },this).extend({ throttle: 500 })
};

Now this does not cause any of the previous errors, but also does not produce any results in HTML ...

I installed the script in

How to correctly apply ko.computed to an object so that I can use the observable and observable array that I have inside the object?

+3
1

, . this .

-, :

var ViewModel = function() {
   this.searchText = ko.observableArray();
   this.taskData = ko.observableArray([]);

   this.filteredRecords = ko.computed(function() {
        //filter logic here, can use `this` and reference searchText/taskData
    },this).extend({ throttle: 500 })
};

, :

ko.applyBindings(new ViewModel(), $('.task-list')[0]); 

viewModel . :

viewModel.filteredRecords = ko.computed(function() {
  //filter logic here, can use `this` and reference searchText/taskData
}, viewModel);

: ,

+6

All Articles