TechnoBuzz

A Techno Blog, mainly about Java

Knockout Custom Bindings

I am continuing to work with KnockoutJs and I noticed a few examples that use custom bindings. This post does a great overview:

Knockout bindings consist of two methods: init and update. Creating a binding is as simple as creating an object with these two methods..

ko.bindingHandlers.yourBindingName = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
  },
  update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
  }
};

The init function – This is usually used to run one-time initialization code or to wire up event handlers …

The update function – provides a way to respond when associated observables are modified….

don’t actually have to provide both init and update callbacks ….

The element parameter – the DOM element that contains the binding…

The valueAccessor parameter – function that gives you access to what was passed to the binding. If you passed an observable, then the result of this function will be that observable (not the value of it). If you used an expression in the binding, then the result of the valueAccessor will be the result of the expression.

The allBindingsAccessor parameter – just a way to pass additional options to the binding, unless you choose to pass an object with multiple properties into your main binding.

The viewModel parameter – provides access to your overall view model for bindings outside of templates.  Most of the time the valueAccessor will give you the data that you want, but the viewModel parameter is particularly useful if you need an object to be your target when you call/apply functions.

ko.bindingHandlers.jqTabs = {
init: function(element, valueAccessor) {
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).tabs(“destroy”);
});
},
update: function(element, valueAccessor, allBindingsAccessor) {
var dependency = ko.utils.unwrapObservable(valueAccessor()), //just to create a dependency
options = allBindingsAccessor().jqTabOptions || {}, //any additional options
selected = $(element).tabs(“option”, “selected”);  //restore selected index

//do in a setTimeout, as the DOM elements are not built yet when we are using bindings to create them
setTimeout(function() {
$(element).tabs(“destroy”).tabs(options).tabs(“option”, “selected”, selected);
}, 0);
}
};

Advertisements

August 22, 2012 Posted by | Uncategorized | | Leave a comment

JQueryUI Tab – The Uncola

Lets say you are using knockoutjs , so your tabs might look something like this in your form data.

< div id=”tabs” data-bind=”jqTabs: { fx: { opacity: ‘toggle’ } }”>
< ul>
{{each tabs}}
< ul>
< li>< a href=”#tab-${id}” data-bind=”click: function(event,ui) {$root.ClickedTab(event,ui);}”>${title}
< /li>< /ul>

Handling the screen interaction is what I am interested in.

Such as the Tab  events.  Getting what was selected .

The  JQueryUI tabs documentation  lists Methods , EventsOptions

For example, under methods,

tabsselect, tabsload, tabsadd

selected: Get or set the selected option, after init.-
var selected = $( ".selector" ).tabs( "option", "selected" );
$('#tabs').tabs("option", "selected")
$('#tabs').data()

$('#tabs').tabs({
        selected: selection.parent().index(),
    });
 

As well the live demos under contents feature information :

Events

A series of events fire when interacting with a tabs interface:

  • tabsselect, tabsload, tabsshow (in that order)
  • tabsadd, tabsremove
  • tabsenable, tabsdisable

Event binding example:

$('#example').bind('tabsselect', function(event, ui) {

    // Objects available in the function context:
    ui.tab     // anchor element of the selected (clicked) tab
    ui.panel   // element, that contains the selected/clicked tab contents
    ui.index   // zero-based index of the selected (clicked) tab

});

tab fiddle  , tab jsbin , tabs stackoverflow

August 15, 2012 Posted by | Uncategorized | , | Leave a comment

Knockout Templating

I am in middle of the use of conditional rendering with knockout.  There are some good articles out there on the use of templates.

http://www.akhildeshpande.com/2012/04/knockout-data-bindings-and-templates.html

http://www.strathweb.com/2012/08/knockout-js-pro-tips-working-with-templates/

http://blog.evereq.com/blog/index.php/2012/03/conditional-template-rendering-with-knockoutjs/

http://www.knockmeout.net/2011/03/quick-tip-dynamically-changing.html

August 10, 2012 Posted by | Uncategorized | | Leave a comment

Knockout Nuggets

1) Send an event on some screen action

Form:

< input type=”button” id=”Button1″ value=”Create My Event” data-bind=”event: { click:createGreatEvent } ” />

Model:

this.createGreatEvent = handleReset;

function handleReset() { alert event(‘Yay’);}

2) Display Label from model

Form:

< label data-bind=”text: myLabel()”>

Model:

this.myLabel = ko.observable(“”);

this.myLabel(“Yay”);

3) Bind to typical form objects

Form:
< tr>
< td data-bind=”with:myObj” >
< textarea size=70 id=’myTextVal’ rows=5 cols=100 data-bind=”value:$data.text” />
< /td>< /tr>
< tr>

< td data-bind=”with:myObj” >
< input type=’checkbox’ id=’displayByDefault’ data-bind=”checked: $data.awesome == ‘Y’ ” />
< /td>< /tr>

< td >
< select id=’questionTypeVal’ data-bind=”options:typeItems, optionsText: ‘text’, value: selectedType, event: {change: changedTypeEvent} ”

</select>
</td>
< /select>
< /td>
Model:

this.myObj = ko.observable(“”);

this.myObj = new Obj(”, ”, ”, ”, ”, ‘N’, ”, ”, ”, ‘Y’);

this.typeItems = ko.observableArray();

// choice list selected

this.selectedType = ko.observable();

this.typeItems.push(new OptionObj(“Text”, “Text Box”));
this.typeItems.push(new OptionObj(“TextArea”, “Text Area”));
this.typeItems.push(new OptionObj(“Date”, “Date”));

this.changedTypeEvent = handleTypeChoice;

function handleTypeChoice() {

if (this.selectedType() != null) {

var type = this.selectedType().id;

}}

4) Conditional Rendering with Templates

Model:

this.SetupQuestions = ko.observableArray();

this.templateToUse = function (item) {

var templateName;

if (item.type == “Text”) {
templateName = “temp1”;
}
else if (item.type == “TextArea”) {
templateName = “temp2”;
}

return templateName;
}

var myViewModel = new myProject();

ko.applyBindings(myViewModel);

myViewModel.SetupQuestions.push({

“myId”: “50001”,
“type”: “Text”
});

myViewModel.SetupQuestions.push({
“myId”: “50002”,
“type”: “TextArea”
});

Form:
< script type=”text/html” id=”temp1″>

< span data-bind=”template: { name: ‘QuestionAnswerChildTemplate’, data: $data }”>< /span>
< /script>

< script type=”text/html” id=”temp2″>

< span data-bind=”template: { name: ‘QuestionAnswerChildTemplate2′, data: $data }”>

< /span>

< /script>

< script type=”text/html” id=”QuestionAnswerChildTemplate”>
< input data-bind=”value : AnswerVal” />
< /script>

< script type=”text/html” id=”QuestionAnswerChildTemplate2″>

< textarea size=70 id=’questionTextVal’ rows=5 cols=100 data-bind=”value : AnswerVal” />
< /script>

< table >
< tbody data-bind=”template: { name: templateToUse, foreach: SetupQuestions }”>< /tbody>
< /table>

August 7, 2012 Posted by | Uncategorized | | Leave a comment

Knockout webosphere

1) Decoupling with Knockoutjs [pluralsight]

2) Knockout js shootout vs other js libraries [  screencast.]

3) data-*

4) Knockout.Unobtrusive

5) Cleaning up knockout

6) Knockout with jSON [1]

7) ESPN api with Knockout  [arrays]

8) Knockout built in binding types

9) Conditional rendering [1]  [2] [3]

10) wiki

August 4, 2012 Posted by | Uncategorized | Leave a comment