我如何在adminhtml中的基因敲除渲染后触发代码运行


11

更新:您可以直接访问视图模型。如果需要触发代码以在渲染后运行,请使用MutationObserver。只要有一个好的示例,我就会发布我的代码。

原始问题: 我们有很多电话打入订单。我正在研究一个模块,该模块会使用webapi / jsonp调用自动在admin->客户->从我们的CRM解决方案中创建数据。这样,magento中的数据不会创建我们已经存储在“主数据库”中的数据重复项。

我剩下要做的一项任务是添加客户的地址。乍一看,这似乎很简单,直到我意识到基因敲除+ magentojs如何在客户表单上呈现一切时,才使我无法捕获模板化元素。在以编程方式删除所有地址并创建新地址之后,我想花些时间来尝试捕获字段集(输入元素)。

如果您想知道为什么要这样做,我的代码的一部分会弹出一个提示,然后说:“嘿,这个人已经存在。您要使用它们吗?” 它将删除您已经输入的所有内容,并以正确的信息替换它。然后呼叫中心对其进行验证,即yadda yadda。

我将分享到目前为止的代码,但是不能正常工作。仅供参考,它扩展了Abstract以捕获“ onUpdate”事件。不要因为试图访问某个收藏夹项目中的收藏夹而责备我。我无法提出一种更好的方法来捕获onUpdate事件并仍然查看所有字段。

我也完全理解哪里出了问题,我只是不知道如何解决它。问题是我假设由.activate()调用生成的元素将在下面立即可用

document.getElementsByClassName('admin__fieldset')

这只是错误的逻辑。理想情况下,我希望能够拉出字段集内容而不必求助于该UI技巧,然后,一旦我完成所有设置,就将其渲染出来。

我不想诉诸jQuery黑客来监视dom更新。

// jsonService variable is available here because it is in the php template render. see
// Stti/Customer/view/adminhtml/templates/javascriptinject.phtml

define(['ko','jquery','underscore','originalAbstract','uiElement', 'uiCollection'], function(ko, $, _, Abstract, Element, Collection) {
    "use strict";

    var theArray = {
        formFields: [],
        getKnockout: (function (ko) {
            return ko;
        })(ko),
        addressButton: null,
        populateFormFields: function () {
            this.formFields = [];

            // Populate the addressButton thinger
            this.addressButton = this.getNewAddressButton();

            var cb = (function(formFields){
                return function (data) {
                    cr(data, formFields);
                }
            })(this.formFields);

            var cr = function (data, formFields) {
                var elems = data.elems();
                for (var i = elems.length - 1; i >= 0; i--) {
                    if (elems[i].hasOwnProperty('uid')) {
                        formFields.push(elems[i]);
                    }
                }
            };

            var fieldsets = document.getElementsByClassName('admin__fieldset');
            for (var i = fieldsets.length - 1; i >= 0; i--) {
                var data = this.getKnockout.dataFor(fieldsets[i]);
                cb(data);
            }

        },
        cleanupAddresses: function () {
            // Remove all addresses
            var fieldsets = document.getElementsByClassName('admin__fieldset');
            for (var i = fieldsets.length - 1; i >= 0; i--) {
                var data = this.getKnockout.dataFor(fieldsets[i]);
                if (data.dataScope.indexOf('data.address') !== -1 && data.childType === 'group') {
                    data.destroy();
                }
            }
        },
        getNewAddressButton: (function () {
            var retVal = null;
            var customerItem = null;

            // Make sure the template is loaded

            var fieldsets = document.getElementsByClassName('admin__page-nav-item');
            for (var i = fieldsets.length - 1; i >= 0; i--) {
                var data = this.getKnockout.dataFor(fieldsets[i]);
                if (data.dataScope === 'data.address') {
                    data.activate();
                } else {
                    customerItem = data;
                }
            }

            // AT THIS POINT, I REALLY WANT KNOCKOUT TO RENDER.  
            fieldsets = document.getElementsByClassName('admin__fieldset');
            for (var i = fieldsets.length - 1; i >= 0; i--) {
                var data = this.getKnockout.dataFor(fieldsets[i]);
                var elems = data.elems();
                if (elems.length === 1 && data.dataScope === 'data.address' && data.index === 'address') {
                    retVal = elems[0];
                }
            }

            // Return the user to the Account Information section
            if (customerItem !== null) {
                //customerItem.activate();
            }

            return retVal;
        }),
        addNewAddress: function () {
            var retVal = null;

            // Use the addressButton to add a child address
            if (this.addressButton) {
                retVal = this.addressButton.addChild();
            }

            this.populateFormFields();

            return retVal;
        },
        onUpdate: function (newValue) {
            if (newValue) {
                this.clearAllFields();
                switch (this.index) {
                    case "email":
                        this.handleEmailBlur(newValue);
                        break;
                    case "constit_id":
                        this.handleConstitBlur(newValue);
                        break;
                }
            }
        },
        handleEmailBlur: function (newValue) {
            // Don't look up anything if the box was cleared out
            if (newValue != null || newValue != '') {
                this.clearAllFields();
                this.makeJsonReq("GetIndividualByEmail?emailaddress=" + newValue + '&callback=?');
            }
        },
        handleConstitBlur: function (newValue) {
            // Don't look up anything if the box was cleared out
            if (newValue != null || newValue != '') {
                this.clearAllFields();
                this.makeJsonReq("GetIndividualByConstit?constit=" + newValue + '&callback=?');
            }
        },
        jQueryByIndex: function (index) {
            function findUIDbyIndex(element) {
                return element.index === index;
            }

            return $('#' + this.formFields.find(findUIDbyIndex).uid);
        },
        makeJsonReq: function (callString) {
            var msg = null;

            $.getJSON(jsonService + callString, (function (localData) {
                    return function (data) {
                        doWork(data, localData);
                    }
                })(this)
            ).done(function () {
                console.log("Json Request Successful");
            }).fail(function () {
                console.log("Json Request Fail");
            }).always(function () {
                if (msg != "") {
                    alert(msg);
                }
            });


            function doWork(individual, localData) {

                // create as many addresses as the individual has
                if (individual != null) {
                    if (individual.NKIUserId != null) {
                        if (individual.NKIUserId != "") {
                            msg = "WARNING! Netforum reports this user has been added to magento with ID " + individual.NKIUserId + ". LOOKUP THE CUSTOMER FIRST AND CONFIRM YOU WANT TO ADD A NEW CUSTOMER!";
                        }
                        //window.location = "/admin";
                    }

                    if (individual.ConstitID != null) {
                        msg = localData.populateFields(individual, localData);
                    }
                    else {
                        msg = "Individual could not be found in NetForum. Verify that this IS a new customer.";
                    }
                }
                else {
                    msg = "Customer's email was not found in netforum. Be sure to use the correct constituent ID if this is an existing customer. A new Netforum customer will be created if it is blank or incorrect.";
                    // prepFormNoUser("constit");

                }
            }

        },
        populateFields: function (individual, localData) {
            // This function is used to get jquerySelector by index

            var getField = localData.jQueryByIndex;

            if (localData.jQueryByIndex('email')) {
                localData.jQueryByIndex('email').val = individual.PrimaryEmailAddress;
            }

            var addresses = null;
            var mageAddresses = [];

            if (individual.Addresses) {
                addresses = individual.Addresses;

                // Populate the form with the addresses
                for (var i = 0; i < addresses.length; i++) {
                    mageAddresses.push(localData.addNewAddress());
                }
debugger;
                var primaryAddress = null;
                for (var i=0; i < addresses.length; i++) {
                    addresses.each(function (e) {
                        try {
                            if (e.IsPrimary) {
                                primaryAddress = e;
                            }

                        } catch (err) {
                            // todo: handle errors
                        }

                        // Populate the billing address if we are on the order screen
                        if (primaryAddress.Id) {
                            if ($('order-billing_address_cxa_key')) {
                                $('order-billing_address_cxa_key').value = primaryAddress.Id;
                                $('order-billing_address_cxa_key').disable();
                            }
                        }
                        if (primaryAddress.Line1) {
                            if ($('order-billing_address_street0')) {
                                $('order-billing_address_street0').value = primaryAddress.Line1;
                            }
                        }
                        if (primaryAddress.City) {
                            if ($('order-billing_address_city')) {
                                $('order-billing_address_city').value = primaryAddress.City;
                            }
                        }
                        if (primaryAddress.Zip) {
                            if ($('order-billing_address_postcode')) {
                                $('order-billing_address_postcode').value = primaryAddress.Zip;
                            }
                        }
                        if (individual.PrimaryPhoneNumber) {
                            if ($('order-billing_address_telephone')) {
                                $('order-billing_address_telephone').value = individual.PrimaryPhoneNumber;
                            }
                        }

                    });
                }
            }

            if (individual.MemberType != null) {
                if ($('group_id')) {
                    var options = $$('select#group_id option');
                    if (individual.MemberType > 0) {
                        options[3].selected = true;
                        $('signup_method').value = "ADMIN-NEWORDER-EXISTING-MEMBER";
                    }
                    else {
                        options[0].selected = true;
                        $('signup_method').value = "ADMIN-NEWORDER-EXISTING-NONMEMBER";
                    }

                    $('signup_method').disable();

                }

                if ($('_accountconstit_id')) {
                    var options = $$('select#_accountgroup_id option');
                    if (individual.MemberType > 0) {
                        options[3].selected = true;
                        $('_accountsignup_method').value = "ADMIN-NEWCUSTOMER-EXISTING-MEMBER";

                    }
                    else {
                        options[0].selected = true;
                        $('_accountsignup_method').value = "ADMIN-NEWCUSTOMER-EXISTING-NONMEMBER";
                    }

                    $('_accountsignup_method').disable();
                }
            }

            if ($('_accountcst_key')) {
                $('_accountcst_key').value = individual.Id;
                $('_accountcst_key').disable();
            }
            if ($('cst_key')) {
                $('cst_key').value = individual.Id;
                $('cst_key').disable();
            }


            if (individual.FirstName) {
                if ($('_accountfirstname')) {
                    $('_accountfirstname').value = individual.FirstName;
                }
                if ($('order-billing_address_firstname')) {
                    $('order-billing_address_firstname').value = individual.FirstName;
                }
            }
            if (individual.LastName) {
                if ($('_accountlastname')) {
                    $('_accountlastname').value = individual.LastName;
                }
                if ($('order-billing_address_lastname')) {
                    $('order-billing_address_lastname').value = individual.LastName;
                }
            }
            if (individual.MiddleName) {
                if ($('_accountmiddlename')) {
                    $('_accountmiddlename').value = individual.MiddleName;
                }
                if ($('order-billing_address_middlename')) {
                    $('order-billing_address_middlename').value = individual.MiddleName;
                }
            }

            if (individual.DateOfBirth) {
                var dob = new Date(parseInt(individual.DateOfBirth.substr(6)));
                var fDob = dob.toString('MM-dd-yyyy');
                if ($('_accountdob')) {
                    $('_accountdob').value = fDob;
                }
            }

            return msg;
        },
        clearAllFields: function () {
            var inputs = $(':input');
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].value = '';
            }

            this.cleanupAddresses();
            this.populateFormFields();
        }
    };

    // Use jQuery to figure out what page we are on.  the body will contain the class matched by name in the
    // view/adminhtml/layout folder
    if ($('body.customer-index-edit').length > 0) {
        return Abstract.extend(theArray);
    }

});

Answers:


3

您可以使用Magento核心提供的afterRender自定义绑定。

这是核心示例。该模板将添加afterRender="setStickyNode"一个在ViewModel上调用setStickyNode函数的模板。

这是另一个基本示例:

我的模板:

<div afterRender="doSomething" id="example1">
    <h1>This is a test</h1>
</div>

我的ViewModel:

return {
    doSomething: function () {
        // Code that will run after id="example1" element is rendered on the page.
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.