4

I'm fairly new to the JavaScript Object Model (JSOM) and I want to do a simple call to get a field value. Very easy in C#, but I can't seem to get a field value even though I have the ListItem:

overrideContext.Templates.Item = customItem;
function customItem(context) {
var title = context.CurrentItem["Title"];
var img = "<img src='" + getImageUrl(1) +  "' />";
return title + img;

function getImgUrl(classID) {
var clientContext = new SP.ClientContext();
var web = clientContext.get_web();
var sourceList = web.get_lists().getByTitle('ClassifiedImages');
var listItem = sourceList.getItemById(classID);


clientContext.load(listItem);
clientContext.executeQueryAsync(Function.createDelegate(this, function () { _returnParam = onSuccess(); }), Function.createDelegate(this, function () { _returnParam = onFail(); }));

return _returnParam;
}

I don't want to use an Async execution. I need the value to be returned immediately. Since I have the listItem, why can't I just say return listItem["Title"]; ??

  • 1
    Even if this were possible, you would lock the UI thread causing the browser to freeze. In most modern browsers your users will very quickly end up being shown a message saying the browser has crashed (i.e. the "Aw, snap!" screen in Chrome). For a single list item on an on-prem server with a good network connection, you might never see this. But for anything non-trivial never lock the UI thread. – Robert Kaucher Apr 12 '14 at 15:18
  • Thanks Robert. This wouldn't be an issue since it only runs on page load and I need the image before even displaying anything. – Michael Colbs Apr 14 '14 at 15:19
4

Natively CSOM only allows for asynchronous calls. If you want to overcome that, you can use a framework such as http://spservices.codeplex.com/

4

You only have a reference to the list item, but the actual list item is not fetched to you from the server until you do the executeQueryAsync.

Not until then do you have any actual information to work with.

  • 2
    +1 Essentially it's an empty shell JS object whose values are filled in with the data returned from the async call to the server. – Robert Kaucher Apr 12 '14 at 15:20
  • 1
    Good answer. To work with jsom you have to think differently opposed to the classic server side code. – Anatoly Mironov Dec 4 '14 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.