javascript - How to pass element parameter to require.js define call? -
i have page split "widgets" loaded dynamically on fly - js require.js, html & css custom js. handy because allows each widget define it's own js requirements.
for example:
define(['jquery', 'mustache'], function($, mustache) { ...
however, in order target widget js functionality correct element, need pass widgets root element javascript, loaded require.js, require.js doesn't support... :/
what have this, define call returns function rendering...
// example.js define(['jquery'], function($) { return function($el) { // render widget here "$el" $el.html('asdsadads'); } });
... run require call...
require(['js/example'], function(render) { render($el); });
... works ok simple structures more complex widgets, init function starts bloat, makes less pretty , harder read (also, more prone bugs).
the optimal situation this...
// example.js define(['jquery'], function($) { if() { // check route and/or other modifiers (is logged in etc) $el.html('asdasdasd'); } else { $el.html('qwerty'); } });
...where actual functionality directly inside define call. unfortunately, far understand, there no way pass element require call, so...
define(['jquery'], function($, $el) {
so, man do? there pattern use somehow pass element cleanly define call? or have resort ugly callback jungle?
the idea of define block return class or function can used in part of code. encourages , re-usable, dry, modular style of coding.
it doesn't make sense define module aware of $el @ point of creation. make sense return class gets instantiated $el. way module reusable , return burden of control application, , not module itself.
simple example of module , use:
define(['jquery'], function($) { var myclass = function(args){ this.initview(args.$el); } myclass.prototype.initview($el){ //init view } return myclass; });
then when can use module this:
define(['path/to/myclass'], function(myclass) { var myview = new myclass({$el: $('.my-selector')}), myotherview = new myclass({$el: $('.my-other-selector')}); });
Comments
Post a Comment