问题
Could I create a function or custom event in a javascript file called "justDidStuff" and then make .live() watch for that being triggered in another jQuery file?
I know this sounds really complicated, but I can't think of another way to do this.
I have new content coming in from the javascript file which is the only infinite scroller known to work for Tumblr.
I have a bunch of styling happening on the layout of the incoming posts (http://syndex.me) which i'm obviously going to make with jQuery. Hence i'm in a situation where I
A) have to use .live() (posts are dynamically loaded) and B) can't trigger the changes in a straightforward manner
In a previous question related to this DOMNodeInserted
was reluctantly suggested. This just listens for when something has been changed, but it slows down pages such as this and has been depreciated.
EDIT
http://marckremers.com/syndex/js/jquery.infinitescrollfortumblr.js Is the javascript file (NB it's a monster)
http://marckremers.com/syndex/js/jquery.syndex.js Is my Styling and Site behaviour jQuery file.
回答1:
You can use bind
and trigger
.
var justDidStuff = function(){
//do some stuff
}
$('something').bind('justDidStuff',justDidStuff); // binds to all elements,
// now and in the future.
//call it:
$('something').trigger('justDidStuff');
回答2:
I think you want to use trigger() and bind
Something like this:
jQuery("body").bind("myEvent", function( data ){ alert("triggered"); } );
and in your function you can notify the page
jQuery("body").trigger("myEvent", { "foo", "bar" });
回答3:
OK I have solved the problem. It's so easy i can't believe it. You live and learn. All I had to do was place jquery code inline within the javascript file by doing this:
jQuery(function ($) {//doStuff in a javascript file as normal, OMG}
来源:https://stackoverflow.com/questions/7985249/possible-when-a-function-in-a-javascript-file-is-triggered-it-lets-a-function