6

Using 2.1.3, I've been trying to bind page elements to internal javascript widget methods, and have been unsuccessful - the docs (http://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-jquery-widgets.html) use the following format:

_bind: function() {
    this._on({
        'click [data-role="menu-item"]:has([data-role="link"])': this._selectItem
    });
}

but within vendor/magento/module-customer/view/adminhtml/web/edit/tab/js/addresses.js, there is another format:

_bind: function () {
    this._on(this.element.find(this.options.addAddressButtonSelector), {
        'click': '_addNewAddress'
    });
}

Is there a preferred format? Neither has been working for me yet.

Update:

This format is working for me (from vendor/magento/theme-adminhtml-backend/web/js/theme.js):

Declare target DOM elements in _create():

_create: function () {
        var selectors = this.options.selectors;

        this.menu = this.element;
        this.menuLinks = $(selectors.topLevelHref, selectors.topLevelItem);
        this.closeActions = $(selectors.closeSubmenuBtn);

        this._initOverlay()
            ._bind();
    },

Then bind widget functions to those elements in _bind():

_bind: function () {
        var focus = this._focus.bind(this),
            open = this._open.bind(this),
            blur = this._blur.bind(this),
            keyboard = this._keyboard.bind(this);

        this.menuLinks
            .on('focus', focus)
            .on('click', open);

        this.menuLinks.last().on('blur', blur);

        this.closeActions.on('keydown', keyboard);
    },

I'd still love to know the preferred/best practice format...

0

We need to make widgets reusable and agile.

All DOM selectors used by a widget must be passed to the widget as options

I think, that second example looks better, according best practices and Magento documentation.

To use variables as the selectors in first example we need to use concatenation of string

_bind: function() {
    this._on({
        'click ' + this.options.selector: handler
    });
}

i think, that this is ugly in comparing with

_bind: function () {
    this._on(this.element.find(this.options.selector), {
        click: handler
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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