-1
\$\begingroup\$

I have this function and not quite sure how to optimize it?

 function _onReadBtnClick(ctx) {

    var data = ctx.props.data;

    // Module Window -- Form Input Values 
    $(".modal-title").text("Intranet Module");
    $("#cBalModel").modal();
    $("#mBalDate").val(data.BalanceingDate);
    $("#mStoreCode").val(data.StoreCode);
    $("#mSubmittedBy").val(data.SubmittedBy);
    $("#mCustCode").val(data.CustomerCode);
    $("#mTicketSO").val(data.Ticket_SO);
    $("#mDollarAmt").val(data.DollarAmount);
    $("#mKeyedIn").val(data.KeyInAs);
    $("#mShouldBeIn").val(data.ShouldBe);
    $("#mAdditionalInfo").val(data.AdditionalInfo);
};
\$\endgroup\$
3
  • \$\begingroup\$ You can ditch jQuery for this bit and store the elements directly into an object/variables. This way, you don't have to re-re-re-re fetch the same elements. Also, only call $("#cBalModel").modal(); after you changed all the text values. This will reduce the number of reflows to 1, instead of many. \$\endgroup\$ Commented Nov 11, 2016 at 13:24
  • \$\begingroup\$ What would that look like? \$\endgroup\$
    – AAH-Shoot
    Commented Nov 11, 2016 at 13:33
  • 1
    \$\begingroup\$ What does the function do? What is the HTML on which it operates? What is ctx? What is data in ctx? \$\endgroup\$
    – mdfst13
    Commented Nov 11, 2016 at 16:45

1 Answer 1

2
\$\begingroup\$

If you can make sure that the fields' IDs have same names like the props, then you can do something like:

Object.keys(data).forEach(function(key) {
    $("#"+key).val(obj[key]);
});
\$\endgroup\$
1
  • \$\begingroup\$ With some memoization, you could speed up this code by quite a bit. An example would be var elems = {}; function _onReadBtnClick(ctx){ [...] Object.keys(data).forEach(function(key) { (key in elems ? elems[key] : elems[key] = $("#"+key)).val(obj[key]); });. This would only fetch the element from the DOM if it isn't already in the object. \$\endgroup\$ Commented Nov 15, 2016 at 8:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.