Question

I'm trying to setup amplifyjs within my MVC4 application. All I'm trying to do a simple server call that returns json data. I got it working in my separate sample project.

But now I'm integrating the same code with my real app. that has following code.

      //sampleservice.js
      amplify.request.define("getSampleData", "ajax", {
          url: "/SampleData/GetSampleData",
          dataType: "json",
          type: "GET"    
      });

      function getSampleData(callbacks) {
            return amplify.request({
              resourceId: "getSampleData",
              success: callbacks.success,
               error: callbacks.error
            });
     };

And this is how I'm trying to consume this in my Jquery.Ready.

    var list;
     $(document).ready(function () {

     list = ko.observableArray([]);
     ko.applyBindings($('#body'));
     getSampleData({
     success: function (data) {
        $(data).each(function (index, item) {
            list.push(item);
        });
    },
    error: function (response) {
        alert(response);
    }
});
 });

I can see my js hitting all the breakpoints yet I'm having this following js exception

    Uncaught amplify.request: unknown resourceId: getSampleData amplify.js:477
    amplify.request amplify.js:477
    getSampleData sampleservice.js:34
    (anonymous function) sampleviewmodel.js:9
    fire jquery-1.9.0.js:1017
    self.fireWith jquery-1.9.0.js:1127
    jQuery.extend.ready jquery-1.9.0.js:416
    DOMContentLoaded

I know its very trivial problem I'm just a newbie with Js programming as you can see and I've spent couple of hours on this but haven't been able to figure anything. If some can guide Or at least some tips to debug it for me here that will be of great help.

Was it helpful?

Solution

You appear not to be using closures so your Amplify definitions are not available. You place your code inside an immediately invoked function expression (iife) as shown below. This will run your amplify definitions code and make the getSampleData available as a property of the dataservice object. So you call dataservice.getSampleData(...)

var dataservice = (function(amplify) {
  var init = function() {
      amplify.request.define("getSampleData", "ajax", {
          url: "/SampleData/GetSampleData",
          dataType: "json",
          type: "GET"
      });
  },

  getSampleData = function (callbacks) {
    return amplify.request({
        resourceId: "getSampleData",
        success: callbacks.success,
        error: callbacks.error
    });
};

init();

return {
    getSampleData: getSampleData
};

})(amplify);

Note that your use of knockout is also not correct. The ko.applyBindings function takes a view model as the first parameter and a DOM element as an optional second parameter. Where is your view model?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top