Tom Rudge Tom Rudge - 2 months ago 14
jQuery Question

Function response recall to Ko viewmodel

My mobile app loads API endpoints at the app login. One of the API endpoints returns data that I can see in the DOM. I need this data loaded into another view/view-model without having to do another API call for the data again.

companyDataService.js - (this returns the api data endpoint that loads on login needed for another view on the app for my view-model)

function getHelpText (companyName, userName, password) {
return api.helpTextGet(company.name, company.userName, company.password);
}


I want the data returned above to be used for my "help text" view-model so it can be passed to the associated view. Here is what I have attempted in my view-model:

var MyText = ko.observable();

var company = shell.authenticatedCompany();
return companyDataService.getHelpText(company.name, company.userName, company.password).then(function (data) {
if (!data) {
MyText(document.getElementById('no-help').innerHTML = '<div class="flex-item"><p>Request help from Support:<br /><a href="mailto:support@company.com" class="low-profile-btn btn btn-lg"><i class="fa fa-info-circle"></i>&nbsp;Contact Support</a></p></div>');
} else {
MyText(data);
}
});



return {
MyText: MyText
};


});

Any ideas on how to do this? pre-loaded data to be used in this view-model? If anybody can help with this would be muchly appreciated as Im pulling my hair out looking at promises, q.defer etc... however I think its a lot simpler than that but just can't manage to work it out.

This is my view ko:

<section class="help-text">
<div class="flex-container">

<div id="no-help" class="help-content" data-bind="html: MyText"></div>

</div>



Answer

companyDataService.js - (this returns the api data endpoint that loads on login needed for another view on the app for my view-model)

function getHelpText(companyName, userName, password) {
        return api.helpTextGet(company.name, company.userName, company.password).then(function (helpText) {
            company.helpText = helpText;
        });
    }

My view model -

      var MyText = ko.observable();

        var company = shell.authenticatedCompany();
        MyText(company.helpText);




    return {
        MyText: MyText
};