Skip to content

Commit

Permalink
Widget: Make contextless widget construction work
Browse files Browse the repository at this point in the history
Due to the fact the widget factory code is now in strict mode, the check for
being called without using the `new` keyword started breaking if you save the
widget constructor to a variable before calling it:
```js
var customWidget = $.custom.customWidget;
customWidget( {}, elem );
```
as then `this` is undefined and checking for `this._createWidget` crashes.
Account for that with an additional check.

Fixes gh-2015
Closes gh-2019
  • Loading branch information
mgol authored Nov 18, 2021
1 parent b52ee40 commit ed637b0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 12 additions & 0 deletions tests/unit/widget/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ QUnit.test( "element normalization", function( assert ) {
$.ui.testWidget();
} );

QUnit.test( "contextless construction", function( assert ) {
assert.expect( 1 );
var testWidget,
elem = $( "<div>" );

$.widget( "ui.testWidget", {} );
testWidget = $.ui.testWidget;

testWidget( {}, elem );
assert.ok( true, "No crash" );
} );

QUnit.test( "custom selector expression", function( assert ) {
assert.expect( 1 );
var elem = $( "<div>" ).appendTo( "#qunit-fixture" );
Expand Down
2 changes: 1 addition & 1 deletion ui/widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ $.widget = function( name, base, prototype ) {
constructor = $[ namespace ][ name ] = function( options, element ) {

// Allow instantiation without "new" keyword
if ( !this._createWidget ) {
if ( !this || !this._createWidget ) {
return new constructor( options, element );
}

Expand Down

0 comments on commit ed637b0

Please sign in to comment.