Hi all,
I'm trying to separate as much of my javascript into an external file as I've noticed a lot of it is repeating. One feature that lies across most of my interface is the 'search' which I use with viewmodel (
http://coderenaissance.github.io/knockout.viewmodel/).
The viewmodel variable name created from
ko.viewmodel.fromModel might be different on each page, but I need to access it to
updateFromModel. I've had a look around and I think
ko.contextFor(this) is what I'm after but I want to make sure if it's doing what I'm expecting.
body.htmlvar myViewModel = ko.viewmodel.fromModel(myViewData, {
extend: {
"{root}.messages[i]": function(item) {
// ...
},
}
});
external.js$('#search-json').on('input', function() {
var viewModel = ko.contextFor(this);
var search_by = $('#search-by').attr('data-search-by');
var url = search_url + "?" + search_by + "_startsWith=" + $(this).val();
// load in message data using our API and this search term
$.getJSON(url, function(data) {
// create observable properties for each of the resource keys from data
ko.viewmodel.updateFromModel(viewModel.$data, data);
});
});
I can then reduce the only global variable to 'search_url'.
If this is the way to refer to the observable, will that also mean I can also separate out my actions? Something like the following (which is currently in body.html):
$('#action-delete').click(function() {
ko.utils.arrayForEach(myViewModel.people(), function(item) {
if (item.isSelected()) {
myViewModel.people.Delete(item);
}
});
});
Would be fine as:
$('#action-delete').click(function() {
var viewModel = ko.contextFor(this);
ko.utils.arrayForEach(viewModel.$data, function(item) {
if (item.isSelected()) {
viewModel.$data.Delete(item);
}
});
});
Cheers,
-Paul