问题描述:

I am using Salt.JS to create a micro-library (sort of like JQuery) for a project. The great thing about Salt.JS is that I can use JQuery like syntax e.g. $('#my_element_id').

I am having a bit of a challenge with making some native extensions. I have the following code:

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

};

which allows me to attach events to Elements, NodeLists, and HTMLCollections like so:

$('#my-element-id').on('click', callback);

$('.all-my-divs').on('click', callback);

However, now I want to attach an on event to window e.g. to enable things like a resize callback. I want to able to do something like this:

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);

What native extension can I make to my existing code to enable this?

网友答案:

What native extension can I make to my existing code to enable this?

You could just alias addEventListener as 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

Many people don't like extending the DOM though, so you may also want to consider writing a wrapper for DOM nodes that you can extend safely.

Here is an example of how you might achieve such a wrapper for a generic node

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));
相关阅读:
Top