Derek
Derek

Reputation: 16311

How to design XPages JS functions for use in library?

Creating XPages application that replaces users filling out a simple Excel and mailing it to users.

So to start with I have two Edit Boxes on the form, Hours10 and Hours20.

Want the value input into Hours20 to also go to Hours10.

When I have this code in the onChange event of the Hours20 edit box

var hours20 = XSP.getElementById("#{id:Hours20}").value; 
XSP.getElementById("#{id:Hours10}").value = hours20; 

It works and the Hours10 edit box is updated with value from Hours20.

When I move the code into a function that is saved in a client side javascript library:

function updateHours() {
  var hours20 = XSP.getElementById("#{id:Hours20}").value; 
  XSP.getElementById("#{id:Hours10}").value = hours20; 
}

and call it from the onChange event of the Hours20 edit box: updateHours();

It does not work. Gives me an object not found error on the XSP object.

Not sure why it is giving error - my guess is that XSP is no longer in Scope?

Any ideas or workarounds?

Upvotes: 0

Views: 1249

Answers (1)

Tim Tripcony
Tim Tripcony

Reputation: 8086

Expression Language (e.g. #{id:Hours20}) can only be interpreted within the context of a component attribute, such as the onChange event code for a field. Once you move the code into a separate library, the code is no longer an attribute of a component, it's code that can be referenced in component attributes.

As with any other good function, design all client-side JavaScript functions to accept anything that might be context-sensitive as a parameter. For example:

function updateHours(inputId, outputId) {
  var hours20 = XSP.getElementById(inputId).value; 
  XSP.getElementById(outputId).value = hours20; 
}

Then your onChange event can reference this function, but pass in only the context-sensitive information:

updateHours("#{id:Hours20}", "#{id:Hours10}");

This way you're keeping reusable business logic in script libraries, which is always a good thing, but nothing in those libraries is assuming anything about page structure or server-side variables.

Upvotes: 9

Related Questions