Accessing behaviors from external JavaScript code

PRELIMINARY INFORMATION - SUBJECT TO CHANGE

Release 2.1 - ...

A behavior can be fully self-contained. Once attached, everything is handled from within event handlers added to HTML elements and when users interact with elements within the area the behavior is attached to, server roundtrips are made from the behavior code.

It is even good practice to make a behavior self-contained. When behaviors have to communicate with the outside world, an elegant way of doing this is to trigger and bind to jQuery events, to create a loosely coupled model in which direct object references are avoided.

However, there may be situations in which you wish to have a main behavior expose public properties or methods that should be accessible to satellite behaviors, or other jQuery code for that matter.

For this, the behavior system has the following solution:

  CopyCode image Copy Code
(function($){
  $.scf.behavior.add("MyBehavior", {
   attach : function (el, args, ui) {
       var me = args.behavior; // behavior instance is passed in args...
       me.publicVar = 1;
   },
   testMethod: function(){
       var me = $.scf.behavior.get("MyBehavior"); // get behavior instance from static method...
       alert(me.publicVar);
   }
  });  
})(jQuery);

Of course, the behavior has to be attached first:

Smartsite SXML CopyCode image Copy Code
{scf.behavior.attach("#test", "MyBehavior")}
<div id="test">Test</div>
<button id="testButton">Call behavior on #test div</button>

Now, to access the behavior from outside code, use the jQuery.scf.behavior.get() method:

  CopyCode image Copy Code
(function($){
  //dom load
  $(function(){
   $("body").on("click", "#testButton", function(e){
       // call behavior testMethod():
       var mb = $.scf.behavior.get("MyBehavior");
       mb.testMethod(); // call the method on the behavior
   });
  });
})(jQuery);