-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\$

closed as unclear what you're asking by forsvarir, Ethan Bierlein, Vogel612, mdfst13, TheCoffeeCup Nov 11 '16 at 19:44

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\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\$ – Ismael Miguel Nov 11 '16 at 13:24
  • \$\begingroup\$ What would that look like? \$\endgroup\$ – AAH-Shoot Nov 11 '16 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 Nov 11 '16 at 16:45
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\$
  • \$\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\$ – Ismael Miguel Nov 15 '16 at 8:58

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