0

I'm new to Knokout. How can I fill an observable array in my view model when a user clicks a button. The object from the server will be large , so I want to use ko.mapping to make them observables.

I have a jsfiddle here: http://jsfiddle.net/russellgove/UXbnz/

RussGove
  • 322
  • 5
  • 18

1 Answers1

1

Updated Fiddle: http://jsfiddle.net/UXbnz/5/

Use ko.mapping.fromJS(FrimServer, {}, this.trades); to update your observableArray with the new data from the server.

I've also taken the liberty to clean up your fiddle a bit.

  1. Use var self = this is common practice when defining your ViewModel in JavaScript. This to avoid problems with closure and scope.
  2. Replaced <label> elements with <span> elements. <label> is meant specifically for assigning labels to input elements.
  3. Moved references to Knockout files to Managed Resources. This is the appropriate way to reference external libraries in a jsFiddle
  4. Added some styling and extra elements for clarity.
  5. Expanded data and displaying of data to showcase possible scenario's.
Martin Devillers
  • 17,293
  • 5
  • 46
  • 88
  • Wow,Thanks for all the help. I went to you modified fiddle, but when I click the gettrades button, it still diesnt display the trade data. Is there somthing I'm missing? – RussGove Sep 06 '12 at 22:18
  • That's weird. It works fine in my browser (Google Chrome). What browser are you using? do you see any errors in the JavaScript console? – Martin Devillers Sep 07 '12 at 07:35
  • OK, I'm using IE8. I dont see any js errors. Let me try it in chrome. – RussGove Sep 07 '12 at 12:25
  • Correction: I was using Ie9 on my personal laptop and do not see the trades. On my work computer running ie8, it works. Does knowkout really work cross-browser, or is this type of issue common? – RussGove Sep 07 '12 at 13:09
  • It's a common issue that actually has nothing to do with your code. The problem is that we're pulling knockout and mapping from `raw.github.com`. GitHub is not a content delivery network and has several catches when you reference files directly from its servers. For one, in IE9 you will see the following error: `SEC7112: Script from https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.debug.js was blocked due to mime type mismatch`. See here for more info: http://stackoverflow.com/questions/5502540/should-github-be-used-as-a-cdn-for-javascript-libraries – Martin Devillers Sep 09 '12 at 09:31
  • hey, thanks for your help. setting the self=this was definitely part of the problem. The other main issue I had was that my knockout code was running in sharepoint. When sharepoint saw the div tag with the data-bind attribute, it didn't send it to the browser (a sharepoint 'quirk;). Once I put the template in a – RussGove Sep 12 '12 at 00:50