I have a question about my knockout ViewModel. I can't access "this" in my jumpToPage (defined in ViewModel) from my click in the template. The subscribeToQuery displays "this" as a UiClass so that i can access other methods from there. I would like to do the same from my jumpToPage method.
Below is my viewmodel:
define(['jquery','ko', 'uiComponent'], function ($, ko, Component) {
"use strict";
self.addresses = ko.observableArray([]);
self.pages = ko.observable(0);
self.q = ko.observable("");
return Component.extend({
initialize : function() {
this._super();
this.getAddresses();
this.subscribeToQuery();
},
getAddresses : function(search, page, limit) {
self.addresses([]);
$.ajax({
url: '/customer/addresses',
type: 'GET',
data: {
p: (page === undefined) ? 1 : page,
limit: (limit === undefined) ? 10 : limit,
search: search
},
complete: function (output) {
var json = JSON.parse(output.responseText);
$.each(json.data, function(index, address) {
self.addresses.push(address);
});
self.pages(json.meta.pages);
}
});
},
subscribeToQuery : function() {
console.log(this);
var that = this;
self.q.subscribe(function(value) {
clearTimeout(self.addressCall);
self.addressCall = setTimeout(function () {
that.getAddresses(value);
}, 300);
});
},
jumpToPage : function(item, event) {
console.log(this);
}
});
}
);
And this is my template:
<input type="text" name="search" placeholder="Zoek een adres" data-bind="value: q, valueUpdate: 'keyup'">
<br />
<br />
<table data-bind="foreach: addresses">
<tr>
<td style="border: 2px solid #e0e0e0; background-color: #efefef; border-radius: 10px;">
<h3 data-bind="text: company"></h3>
<small data-bind="text: firstname"></small>
<small data-bind="text: lastname"></small>
</td>
</tr>
<tr><td style="height: 2px;"></td></tr>
</table>
<div data-bind="foreach: new Array(pages())">
<button data-bind="text: $index()+1, click: $parent.jumpToPage" style="cursor: pointer"></button>
</div>
Can anyone please help? Thanks in advance!
Best Answer
old post but this might help someone.
You just need to define a global variable before extending your component and assign the component context in initialize.
Then you can you self in your function.