Conventional jQuery function works using my_function() but elgg.my_plugin.my_function doesn't work?
info@elgg.org
Security issues should be reported to security@elgg.org!
©2014 the Elgg Foundation
Elgg is a registered trademark of Thematic Networks.
Cover image by RaĆ¼l Utrera is used under Creative Commons license.
Icons by Flaticon and FontAwesome.
Yeah I can't see why that would be the case, I'm working with jquery in a module right now and that's not happening. Perhaps you have a click trigger happening in js elsewhere?
I only have 3 triggers for the landing page, I'd need to investigate this more. I do like the concept of just loading a specific JS one time or multiple times when needed.
My thoughts on this:
1. Extend elgg.js if you need the code to run on each page, but wrap your js in async require() regardless
require(['elgg','jquery'], function(elgg, $) {
// do stuff
});
So far, I only had to do this in very rare cases. You most likely can avoid clogging runtime. You can usually do the same thing from within a view that needs to load an AMD module.
2. Write AMD modules in such a way that doesn't perform any actions, rather return an object or prototype that can be instantiated or called from another script. AMD is only loaded once even if you call a module multiple times in different places on a page.
// and module my_plugin/my_module.js
define(function(require) {
return function(arg) {
};
});
// async require call that can go in a view
require (['my_plugin/my_module'], function(mod) {
mod(arg); // runs actual code
});
3. Proxy event bindings. Use $(document).on(event, selector, callback) pattern, and use data attributes to pass in parameters. Always assume that the element is not present on the page when your JS runs. Proxying binds the callback to all elements currently present on the page, and others that may be appended to the page later.
4. Assume that any view can be loaded via ajax. Use inline require() calls wrapped in a script tag in your views rather than elgg_require_js() (sounds like a bad advise, but it's a safer pattern, see ckeditor instantiation patterns). elgg_require_js() only runs server side.
5. Avoid global scope. AMD module is cached, so you can use it to store variables.
// and module module.js
define(function(require) {
return {
'param1': 0,
'callback1': function() {
}
};
});
// load in view 1
requre(['module'], function(mod) {
console.log(mod.param1); // outputs 0
mod.param1 = 1;
});
// load in view 2
requre(['module'], function(mod) {
console.log(mod.param1); // outputs 1
mod.callback1();
});
I just uploaded an example plugin that might help you with moving to AMD modules. Very simple.
https://elgg.org/plugins/2445848
@rcrowe thanks, I'll take a look at it!
- Previous
- 1
- 2
- 3
- 4
- Next
You must log in to post replies.