Events

优质
小牛编辑
139浏览
2023-12-01

Event binding

jQuery event binding

Bind events with jQuery with standard jQuery event methods .on(), .off(), and .one().

// jQuery
var $grid = $('.grid').masonry({...});

function onLayout() {
  console.log('layout done');
}
// bind event listener
$grid.on( 'layoutComplete', onLayout );
// un-bind event listener
$grid.off( 'layoutComplete', onLayout );
// bind event listener to be triggered just once. note ONE not ON
$grid.one( 'layoutComplete', function() {
  console.log('layout done, just this one time');
});

jQuery event listeners have an event argument, whereas vanilla JS listeners do not.

// jQuery, has event argument
$grid.on( 'layoutComplete', function( event, items ) {
  console.log( items.length );
});

// vanilla JS, no event argument
msnry.on( 'layoutComplete', function( items ) {
  console.log( items.length );
});

Vanilla JS event binding

Bind events with vanilla JS with .on(), .off(), and .once() methods.

// vanilla JS
var msnry = new Masonry( '.grid', {...});

function onLayout() {
  console.log('layout done');
}
// bind event listener
msnry.on( 'layoutComplete', onLayout );
// un-bind event listener
msnry.off( 'layoutComplete', onLayout );
// bind event listener to be triggered just once
msnry.once( 'layoutComplete', function() {
  console.log('layout done, just this one time');
});

Masonry events

layoutComplete

Triggered after a layout and all positioning transitions have completed.

// jQuery
$grid.on( 'layoutComplete', function( event, laidOutItems ) {...} )
// vanilla JS
msnry.on( 'layoutComplete', function( laidOutItems ) {...} )

laidOutItems Array of Masonry.Items Items that were laid out

$grid.on( 'layoutComplete',
  function( event, laidOutItems ) {
    console.log( 'Masonry layout completed on ' +
      laidOutItems.length + ' items' );
  }
);

removeComplete

Triggered after an item element has been removed.

// jQuery
$grid.on( 'removeComplete', function( event, removedItems ) {...} )
// vanilla JS
msnry.on( 'removeComplete', function( removedItems ) {...} )

removedItems Array of Masonry.Items Items that were removed

$grid.on( 'removeComplete',
  function( event, removedItems ) {
    notify( 'Removed ' + removedItems.length + ' items' );
  }
);