From 85292d9558472686321ff12d973cdb5c65f823ff Mon Sep 17 00:00:00 2001 From: RubaXa Date: Mon, 9 Feb 2015 18:10:20 +0300 Subject: [PATCH] #236: + ngSortEvent --- README.md | 8 +++++++- ng-sortable.js | 44 +++++++++++++++++++++++++++++++------------- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index d548c23..132d385 100644 --- a/README.md +++ b/README.md @@ -274,7 +274,13 @@ angular.module('myApp', ['ng-sortable']) $scope.items = ['item 1', 'item 2']; $scope.foo = ['foo 1', '..']; $scope.bar = ['bar 1', '..']; - $scope.barConfig = { group: 'foobar', animation: 150 }; + $scope.barConfig = { + group: 'foobar', + animation: 150, + onSort: function (/** ngSortEvent */evt){ + // @see https://github.com/RubaXa/Sortable/blob/master/ng-sortable.js#L18-L24 + } + }; }]); ``` diff --git a/ng-sortable.js b/ng-sortable.js index d4fe47f..ec4aba6 100644 --- a/ng-sortable.js +++ b/ng-sortable.js @@ -14,6 +14,16 @@ })(function (angular, Sortable) { 'use strict'; + + /** + * @typedef {Object} ngSortEvent + * @property {*} model List item + * @property {Object|Array} models List of items + * @property {number} oldIndex before sort + * @property {number} newIndex after sort + */ + + angular.module('ng-sortable', []) .constant('$version', '0.3.5') .directive('ngSortable', ['$parse', function ($parse) { @@ -58,12 +68,20 @@ ; - 'Start End Add Update Remove Sort'.split(' ').forEach(function (name) { - options['on' + name] = options['on' + name] || function () {}; - }); + function _emitEvent(/**Event*/evt, /*Mixed*/item) { + var name = 'on' + evt.type.charAt(0).toUpperCase() + evt.type.substr(1); + + /* jshint expr:true */ + options[name] && options[name]({ + model: item, + models: source.items(), + oldIndex: evt.oldIndex, + newIndex: evt.newIndex + }); + } - function _sync(evt) { + function _sync(/**Event*/evt) { var oldIndex = evt.oldIndex, newIndex = evt.newIndex, items = source.items(); @@ -101,27 +119,27 @@ }, { onStart: function (/**Event*/evt) { nextSibling = evt.item.nextSibling; - options.onStart(source.items()); + _emitEvent(evt); scope.$apply(); }, - onEnd: function () { - options.onEnd(source.items()); + onEnd: function (/**Event*/evt) { + _emitEvent(evt, removed); scope.$apply(); }, onAdd: function (/**Event*/evt) { _sync(evt); - options.onAdd(source.items(), removed); + _emitEvent(evt, removed); scope.$apply(); }, onUpdate: function (/**Event*/evt) { _sync(evt); - options.onUpdate(source.items(), source.item(evt.item)); + _emitEvent(evt, source.item(evt.item)); }, - onRemove: function () { - options.onRemove(source.items(), removed); + onRemove: function (/**Event*/evt) { + _emitEvent(evt, removed); }, - onSort: function () { - options.onSort(source.items()); + onSort: function (/**Event*/evt) { + _emitEvent(evt, source.item(evt.item)); } }));