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...

asked Jan 6, 2017 at 16:45

1 Answer 1

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
 });
}
answered Jan 15, 2017 at 20:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.