PDA

View Full Version : Resolved Require JS and triggering a method from another module after page-load



dog
01-07-2015, 07:54 PM
Hi there,

Context:
I'm working on a site that uses require.js to define several controllers, modules and utilities. One util (called utils/forms) adds bespoke controls to all input[type=number] elements that it encounters on page load. I then have a module (called mods/addAnother) that takes a block of markup and appends a cleaned-up copy of it to a given element. That's all good!

Issue:
When using mods/addAnother on a section containing number inputs I'm encountering a problem. The problem is that in utils/forms, events on the bespoke number buttons are bound to make them operational, this happens on page load so the number buttons added by mods/addAnother don't have the binding and therefore aren't operational. I'm struggling to trigger the bind method of utils/forms when the appropriate method of in mods/addAnother runs.

Is this a common issue ...triggering a method defined in one module via a callback in another module? Does require.js (or Javascript in general) allow me to do this in some reasonably simple way that I'm not aware of?

Any help will, as always, be much appreciated.

Thanks,
Laurence

dog
01-08-2015, 03:41 PM
In short... I want to trigger a method from one module from a method in another module but I don't know how to do it.

dog
01-09-2015, 05:10 PM
Having read-up on require.js (via http://requirejs.org/docs/api.html) I realise this is pretty straight forward. A module can return its methods making them assessible to other parts of the code base. In this case I wanted to assess the method "bindUpDownButtons" (of utils/forms) and trigger it from mods/addAnother.

In require.js it can be done like this...

Forms.js looks a bit like this:



define(function(require){

// lots of code omitted

var NumberFields = {

// lots of methods relating to number fields

bindUpDownButtons : function($field){
// the code of interest
}
};

// export these methods
return { init : init, NumberFields : NumberFields };
});


Then in addAnother.js the important bit is here:



// ...

var addSet = function(config){
// code that sets up and adds new set here

// Special treatment for sets that contain number fields
if($newHtml.find('input[type=number], input[data-type=number]').length > 0){

// Ensure that custom number buttons are bound
require(['utils/forms'], function(forms) {
$newHtml.find('input[type=number], input[data-type=number]').each(function(){
forms.NumberFields.bindUpDownButtons($(this));
});
});
}

// rest of code
};



Hope this helps anyone who comes across the same lack of knowledge.

Cheers!
:cool: