4

I've got a series of apps that are embedded via Javascript in a variety of pages, so it's important to be as careful as possible about constructing selectors in a way that don't accidentally select something on the parent page. (I have no control over the parent markup, and iframes are not an option.)

The parent pages all use jQuery in .noConflict() mode, and my app always lives inside a div with the class my_app_class

(function($) {
    var el = $(".my_app_class"); //my code

}(window.jQuery));

While I'm pretty good about always remembering to prepend my jQ selectors with "my_app_class", I would be more comfortable if that was implicit in $. Essentially, I would like:

$(".headline")

To always equal:

$(el).find(".headline")

The naïve way to do this would be like this:

$ = function(selector) {
    return jQuery(el).find(selector);
}

But I would like to maintain a super function for situations when I really do need to make a selection on the parent page (which does happen from time to time). I also don't want to overwrite other uses of jQuery like $.ajax.

What's the best was to alias a function and maintain the original? I want something like this

(new $) = selection inside `.my_app_class`

($$) = (old $)

Thanks!

4

1 回答 1

0

What you are attempting is a bit of a maintenance headache. If anyone else picks up your code they will get very confused trying to mentally convert jQuery syntax into what you want it to do.

If you instead write your code as simple jQuery plugins, applied to the appropriate classes. Then:

1) you will find they will naturally apply to only the relevant elements, without hacking jQuery itself and

2) you suddenly have scope to apply them to dynamically loaded content (again based on the classes, but this time in the loaded content).

There are many models out there for writing code as plugins. A simple one being the jQueryUI $.widget

于 2015-04-20T10:13:58.270 回答