Object merging and extending
When attaching Scf Behaviors to elements, you can pass settings that can be used by the behavior.
Consider the following piece of HTML:
| Smartsite SXML |
|
|---|---|
<form action="?" method="post"> <fieldset> <button id="myButton" type="submit">Haha</button> </fieldset> </form> |
|
Attach a behavior to #myButton by using Scf (see also smartlet.behavior.attach()):
| Smartsite SXML |
|
|---|---|
{scf.behavior.attach("#myButton", MyConfirmBehavior,
confirmText, "Really?"
)}
|
|
... or directly by using Javascript:
| Smartsite SXML |
|
|---|---|
<se:placeholder.addjavascriptonload>
$j("#myButton").scf.behavior("MyConfirmBehavior", {
confirmText: "Really?"
});
</se:placeholder.addjavascriptonload>
|
|
The behavior gets the options in the second argument (options) to the attach method.
| Smartsite SXML |
|
|---|---|
<se:placeholder.addjavascript>
$j.scf.behavior.add('MyConfirmBehavior', {
attach: function(element, options, obj){
obj.click(function(){
if(!confirm(options.confirmText))
return false;
});
}
});
</se:placeholder.addjavascript>
|
|
... but what if the behavior is attached without
| Smartsite SXML |
|
|---|---|
{scf.behavior.attach("#myButton", MyConfirmBehavior)}
|
|
You will of course have to test whether the options have been provided:
| Smartsite SXML |
|
|---|---|
<se:placeholder.addjavascript>
$j.scf.behavior.add('MyConfirmBehavior', {
attach: function(element, options, obj){
if(options != null){
if(options.confirmText == null)
options.confirmText: "Are you sure?",
if(options.extensions == null)
options.extensions: "doc,docx,ppt,pptx,pps,ppsx,pdf"
}
obj.click(function(){
if(!confirm(options.confirmText))
return false;
});
}
});
</se:placeholder.addjavascript>
|
|
jQuery provides an easy way to shorten this:
|
|
|
|---|---|
if(options != null){
if(options.confirmText == null)
options.confirmText: "Are you sure?",
if(options.extensions == null)
options.extensions: "doc,docx,ppt,pptx,pps,ppsx,pdf"
}
|
|
Especially with a lot of defaults in your Behavior settings, this can become quite verbose and repetitive.
Luckily, there's jQuery.extend().
... can be rewritten as:
|
|
|
|---|---|
$j.extend(options, {
confirmText: "Are you sure?",
extensions: "doc,docx,ppt,pptx,pps,ppsx,pdf"
});
|
|
This makes things easier to read and maintain.