I have a method inside my viewModel that gets calls an ajax get method to fetch all of the items. This all works perfect. I then have a ko.bindingHandler that is used to inline upload images via ajaxSubmit. This also works, but the issue is I have to duplicate code that fetches all of the items inside the bindingHandler that uploads the images or else the image wont update once uploaded. Refreshing the page fixes the issue but I want to have the view auto refresh with the new image. So the real question is it possible to call a function from the viewModel inside a bindingHandler? Any help would be greatly appreciated!
BindingHandler:
ko.bindingHandlers.imageInLineUpload = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
property = ko.utils.unwrapObservable(options.property);
$(element).change(function () {
if (element.files.length) {
if ((element.files[0].type === "image/png") || (element.files[0].type === "image/jpeg")) {
var $this = $(this);
$(element.form).ajaxSubmit({
url: $.API.url + "XYZ",
type: "POST",
dataType: "text",
success: function (data) {
toastr.success('Upload Successful.');
var viewModel= new MyViewModel ();
viewModel.GetObjects();
},
error: function (jqXHR, textStatus, errorThrown) {
toastr.error('Upload Failed. Please Try again!');
}
});
}
else {
toastr.error('Upload Failed. PNG and JPEG are the only supported formats.');
}
}
});
}
};
ViewModel:
var MyViewModel = function () {
var self = this;
self.xyz = ko.observable("");
self.xyz = ko.observable("");
self.xyz = ko.observable("");
self.GetObjects= function () {
// Ajax call to fetch objects.
}
self.GetObjects();
};
ko.applyBindings(new MyViewModel ());