我正在使用Salt.JS为一个项目创建一个微库(有点像JQuery)。Salt.JS的好处是我可以使用JQuery的语法,例如:$('#my_element_id')
.
我在制作一些本地扩展时遇到了一点挑战。我有以下代码:
window.Element.prototype.on = function(eventType, callback) {
//code here
};
window.NodeList.prototype.on = function(eventType, callback) {
//code here
};
window.HTMLCollection.prototype.on = function(eventType, callback) {
//code here
};
允许我将事件附加到元素,NodeLists,和HTMLCollections,像这样:
$('#my-element-id').on('click', callback);
$('.all-my-divs').on('click', callback);
然而,现在我想将on
事件附加到window
,例如启用诸如调整大小回调之类的事情。我希望能够做这样的事情:
var resized = function(){
console.log('ALWAYS BE RESIZING!');
};
var el_win = $('window'); //I've updated Salt.JS to return window object
el_win.on('resize', resized);
我可以对我现有的代码做什么本地扩展来启用这个?
我可以对我现有的代码做什么本地扩展来启用这个?
可以将addEventListener别名为on
if (!('on' in Window.prototype)) // don't shadow if it exists
Object.defineProperty(Window.prototype, 'on', {
value: Window.prototype.addEventListener,
configurable: true // let other things make changes to this too
});
// now, e.g.
window.on('click', console.dir.bind(console)); // works the same as addEventListener
许多人不喜欢扩展DOM,因此您可能还需要考虑为DOM节点编写一个可以安全扩展的包装器。
下面是如何为通用节点实现这种包装器的示例
function wrap(node) {
var o = {node: node}, i,
map = [
{alias: 'on', native: 'addEventListener'},
{alias: 'off', native: 'removeEventListener'}
];
if (node && node.constructor && node.constructor.prototype)
for (i = 0; i < map.length; ++i)
if (map[i].native in node.constructor.prototype)
o[map[i].alias] = node.constructor.prototype[map[i].native].bind(node);
return o;
}
// now, e.g.
wrap(window).on('click', console.dir.bind(console));