我正在使用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);然而,现在我想给window附加一个on事件,比如启用一个调整大小的回调。我希望能够做这样的事情:
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);我可以对现有代码进行什么本机扩展来实现这一点?
发布于 2015-05-23 22:49:20
我可以对现有代码进行什么本机扩展来实现这一点?
您可以将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));https://stackoverflow.com/questions/30413990
复制相似问题