javascript - RequireJS Load Module Gone Wrong? -


using requirejs, planning load module in page, example home page, (for sake of reading, have translated code coffeescript javascript):

require(["tmp/assets/scripts/modules/_image"], function(_image) {   return $('ul li img')._image.basicimagehover(); }); 

and im _image.js file:

$.fn.basicimagehover = function() {   $(this).on('hover', function() {     $(this).parent().find('div.caption').slideup('fast');     return $(this).css('opacity', '.5');   });   return this; }; 

my project structure (sorry don't know how draw better graphs):

  • tmp/assets/scripts/modules/_image.js
  • tmp/assets/scripts/front/home.js

error in console said @ home.js _image undefined, i'm guessing changing module return function instead of plugin might work, wondering wrong current setup. can explain? thanks

there couple problems code.

first, there's problem of how access jquery plugin. these install on jquery objects, won't them through requirejs. code in particular not think does:

require(["tmp/assets/scripts/modules/_image"], function(_image) {   return $('ul li img')._image.basicimagehover(); }); 

the part $('ul li img')._image.basicimagehover() going evaluated field named _image value returned $('ul li img'). has nothing whatsoever value of _image argument of function. need this:

require(["tmp/assets/scripts/modules/_image"], function() {   $('ul li img').basicimagehover(); }); 

i've removed return because useless in callback passed require. (there's sensible return value. requirejs receives value goes after this.) there's no need _image argument because jquery plugin show in code installs on instances of jquery.

second, _image.js file should call define amd-compliant:

define(['jquery'], function ($) {    $.fn.basicimagehover = function() {     $(this).on('hover', function() {       $(this).parent().find('div.caption').slideup('fast');       return $(this).css('opacity', '.5');     });   }; }); 

i've removed return statement because serves no purpose here either. code above entails must configure requirejs know jquery , load it. if in situation jquery loaded outside , before requirejs, make define define([], function () {.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -