Magento2 – _create Function in Custom require.js Not Called

magento2requirejs

I am creating a custom js for my module.

app/code/Namespace/Module/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            myjs:'Namespace_Module/js/myjs'
        }
    }
};

app/code/Namespace/Module/view/frontend/web/js/myjs.js

define([
    "jquery",
    "underscore",
    "jquery/ui"
],
    function($, _){
        console.log('1');
        $.widget('mage.myjs', {
            options: {
                divId: '',
                ajaxUrl: '',
                isNeedLast: false,
                autoSubmit: false,
            },
            selects: [],
        _create: function() {
            console.log('inside create'); // this log is not displayed
        }
    });

    return $.mage.myjs;

});

and calling it in the phtml like below :

require(['jquery', 'myjs'], function($) {
        var finderConfig = {"ajaxUrl":"<?php echo $block->getAjaxUrl() ?>","isNeedLast":1,"autoSubmit":1};
        finderConfig.divId = 'finder_<?php echo $finderID ?>';
        $("#finder").myjs(finderConfig);
    });

here the console.log('1') is displayed but the console.log('inside create') inside _create function is not displayed.

cany anyone point out what i am missing.Thanks.

Best Answer

Add below code in your phtml file.

<div id="finder"></div>
<script>
    require(['jquery', 'myjs'], function($) {
        var finderConfig = {"ajaxUrl":"<?php echo $block->getAjaxUrl() ?>","isNeedLast":1,"autoSubmit":1};
        finderConfig.divId = 'finder_<?php echo $finderID ?>';
        $("#finder").myjs(finderConfig);
    });
</script>

I think you are missing div with id="finder" in your code. please check it with this code.

let me know if you have any issue.