ded / script.js

Asyncronous JavaScript loader and dependency manager
MIT License
2.95k stars 340 forks source link

Dynamic event binding? #73

Closed Aristona closed 10 years ago

Aristona commented 10 years ago

Hi,

In my current project, I depend on jQuery. However, if the jQuery exists in page already, I need to skip it.

For example:


if( ! page.has('jquery') )
     $script('http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js', 'jquery');

$script('query', function() {
      app.run();
});

When page already uses jQuery, this script does not work.

How can I bind the jquery event manually myself?

e.g

if(page.has('jquery'))
     $script.bindEvent('jquery');
else
     $script('http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js', 'jquery');

If this use is not supported, is there any elegant way to do it?

ded commented 10 years ago
function doJQueryStuff() {
  $('p').append('<span>hello</span>')
}

if (typeof jQuery === undefined) $script('ajax.googleapis.com/jquery.js', doJqueryStuff)
else doJQueryStuff()
Aristona commented 10 years ago

Thanks for the reply, but how do you run this callback with the code above? I've tried your solution with many combinations but this one never runs like that.

$script('query', function() {
      app.run();
});

What should I write inside the doJqueryStuff function so $script('doJqueryStuff ') executes?

ryanve commented 10 years ago

doJQueryStuff is just an example name. The point is to used a named function as the callback so that you can call it immediately when your dependency is already loaded and otherwise pass it as a callback to $script

Aristona commented 10 years ago

Hi,

I'm a bit confused. Do you tell me to do this?

if(typeof jQuery === undefined) {
    $script('http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js', 'jQuery');
} else {
    dojQueryStuff();
}

$script('jQuery', function() {
       app.run();
});

function dojQueryStuff() {
    app.run();
}

If so, this is not what I want. (since I'll be duplicating what I write in the jQuery callback in the else (or another function in your case) Can I instead do something like this?

if(typeof jQuery === undefined) {
    $script('http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js', 'jQuery');
} else {
    $script.fireEvent('jQuery');
}

$script('jQuery', function() {
       app.run();
});

Because this looks way more elegant.