I wrote a small jQuery plugin that claims to do this.
How to use?
Use on
jQuery function (that is actually rewritten by my plugin) like below:
<script src="path/to/jQuery.js"></script>
<script src="path/to/jQuery-priorityze.js"></script>
<button id="go">Test 1</button>
<script>
var $go = $("#go");
$go.on('click', 5, function () { console.log('nice'); });
$go.on('click', {priority: 4}, function () { console.log('a'); });
$go.on('click', 6, function () { console.log('plugin?'); });
$go.on('click', 1, function () { console.log('Is'); });
$go.on('click', 3, function () { console.log('this'); });
$go.on('click', 2, function () { console.log('not'); });
<script>
If priority is not provided the plugin will choose the priority of the event incrementing 1
to the latest provided priority.
How to use in your example
I was hoping to get a solution without changing existing structure
Include my plugin in the page and use this:
$("#b1").on('click', function (){alert('1');}); // 1
$("#b1").on('click', function (){alert('2');}); // 2
$("#b1").on('click', function (){alert('3');}); // 3
$("#b1").on('click', 1.5, function (){alert('4');}); // 1.5
// 0 -> 1 -> 4 -> 2 -> 3
// seems that onclick attribute is stronger that .on
function topPriority() {
alert('top priority');
}
Setting 1.5
priority puts the last handler between the first (1
) and second (2
) one.
Like I commented onclick
attribute is stronger than on
jQuery function.
UPDATED JSBIN
Source code
Checkout the source code here on Github and check the tests.
Don't forget to star fork it: https://github.com/IonicaBizau/jQuery-prioritize :-)
How does it work?
The plugin is compatible with jQuery >= 1.8.x
and it uses $._data($el[0]).events
like it was described here.
Contributing
Do you want to contribute to this project? Great! Follow the following steps:
- Search in the repo issues an issue you want to fix.
- If you want to add a new feature that is not added as issue, add it first in the issue list.
- Fork the project to your profile.
- Fix the issue you want to fix.
- Make a pull request.
I will try to merge the pull requests as fast I can.