Getting a reference to a behavior

In the last post, I showed how you can instantiate multiple behaviors on a single input element, through server extenders or directly through client behaviors (which themselves can be created imperatively or declaratively). In this post, I want to show how to get a reference to these behaviors.

Of course, the simplest is to grab that reference when you create the behavior and hold on to it until the next time you need it:

var tb1EditInPlace =
    $create(Bleroy.Sample.EditInPlace, { cssClass: "editInPlace" },
            {}, {}, $get('tb1'));

Now of course, the code that needs to use a reference might not be from the same source or area of responsibility as the one that created it. If you created the behavior through declarative markup, for example (the framework creates the instance in this case, not your application directly).

Fortunately, getting a reference to a behavior is very simple and can be done in a number of ways. First, you can give it an explicit id:

$create(Bleroy.Sample.EditInPlace,
        { id: "tb1EditInPlace", cssClass: "editInPlace" },
        {}, {}, $get('tb1'));

You can then retrieve it by just calling Sys.Application.findComponent, or $find for short:

var ref = $find('tb1EditInPlace');

Even if you don’t define an explicit id though, we’ll define one for you. The default id for a behavior is the id of the element concatenated with a ‘$’ character and the type name of the behavior. So if you defined the behavior this way:

$create(Bleroy.Sample.EditInPlace,
        { cssClass: "editInPlace" }, {}, {}, $get('tb1'));

You can then reference it like so:

var ref = $find('tb1$EditInPlace');

You can also define a name for the behavior instead of an id and this will pretty much replace the default (which we just saw is the type name):

$create(Bleroy.Sample.EditInPlace,
    { name: "inplace", cssClass: "editInPlace" },
    {}, {}, $get('tb1'));

And then reference the behavior this way:

var ref = $find('tb1$inplace');

The behavior is also added to the element as an expando attribute that has the same name as the behavior. This means that in the previous case, this will also work:

var ref = $get('tb1').inplace;

And in the ones before that:

var ref = $get('tb1').EditInPlace;

The key takeaway here is that it is always possible to get a reference to a behavior no matter how or where it was created.

No Comments