TechnoBuzz

A Techno Blog, mainly about Java

FOUC! (Flash of Unstyled Content)

It occurs when applying styles with JavaScript on page load.

The problem is most evident when there is some content that needs to be hidden initially and when the document is large or complex.

< ul id=”flash” >

In the On Ready function , you would apply :

$ (‘#flash’).hide();

A whole lot of document that has to be ready before anything inside the ready() function can be executed.

Putting the tags just inside the closing  body tag doesn’t help either

http://www.learningjquery.com/2008/10/1-way-to-avoid-the-flash-of-unstyled-content

Advertisements

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

Fluff 2012 August Notes on Advanced Javascript

I just attended the NFJS Raleigh tour stop. This was my third time at this great event and my focus of the sessions was javascript and mobile.

Here begins my notes:

Suggested Book: Seven Languages in Seven weeks by Bruce Tate

Prototypes – IO, LUA, SELF : access to class , define on the fly, manipulate class after you define it.

Functional JS vs OO JS

http://joda-time.sourceforge.net/ – spring data

Everything in javascript is an object but primitives.  Objects consist of key value pairs + prototype

javascript function is pass by reference not by copy.

Dynamic typed language

hoisting –  Only functions create a new scope.

propertyIsEnumerable : higher within prototype

passing functions to a function desirable for reuse

associative array {name: ‘fred’}

two scopes: global and function level scope

this – scope you are in

null == undefined

parasitic inheritance is like composition

CommonJS – use of require

Underscore.js

Date.js

Sugar.js

Backbone.js

Testing- Jasmine

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

 

September 4, 2012 Posted by | Web Design | | Leave a comment

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);
}
};

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 jQuery Binding and Visibility

Reading more on Knockout js

Here is the panel we will enable or disable:

< div id=”optionalPanel” style=”color: red;” data-bind=”visible:isEnabled”>The following is an example div</div>

Here we have a button that sends an event when it is clicked

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

Here is what the associated binding  (javascript) looks like:

function viewModel() {
   var self = this;

    myValues = ko.observableArray([]);

    this.isEnabled = ko.computed(function () {   return myValues().length > 0;  }    );

    // Here when er receive event we enable div tag by making size of myValues greater than zero

    buttonEvent = function (selectedSection, userAction) { myValues.push(“some value”);   };

};

//Must apply a model to bindings
ko.applyBindings(new viewModel());

The documentation for this example (also an example with booleans).

Likewise, here is an example of using anonymous function in html to reference the javscript bindings.

A  dropdown  binding example

More binding techniques

Site point series : 1 2 3

special comments for “if” binding

select list  example (i.e. picklist) , alternate select list example

July 21, 2012 Posted by | Uncategorized | , | Leave a comment

Knockout jQuery

In the GWT ecosystem , the Model View Presenter (MVP) pattern is the architecture of choice. However, the model requires some special capabilities when  dealing with the state (i.e. what the user did should force some special visibility rules).

In MVP the model typically refers to just the domain objects that will be displayed, things like a Customer, Contact or Account. From a Presentation Model perspective the term model encompasses the domain data plus all additional state that can change during the normal operation of the UI.

Likewise, pure javascript libraries have to deal with these type of issues too. They have a name for the MVP + (Editors/Pectin) pattern.  Its called MVVM.

Model–View-ViewModel talks of creating a new model (in addition to your domain model). This model normally adds additonal properties from the prespective of View (as we understand that View has controls in addition to data which it’s displaying).

Knockout  handles data binding :  “Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes)”.

A simple example always explains it best.

The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model.

For example, let us imagine that we have a model containing a date attribute in unix format (e.g 1333832407). Rather than our models being aware of a user’s view of the date (e.g 04/07/2012 @ 5:00pm), where it would be necessary to convert the address to it’s display format, our model simply holds the raw format of the data. Our View contains the formatted date and our ViewModel acts as a middle-man between the two.

KnockoutJS interprets the ViewModel as the represtation of data and operations that can be performed on a UI. 

Another simple example with code.

The intent of Knockout and other MVVM framework offerings is to move those conditional logic statements into the ViewModel and let the ViewModel be the sole source of the business logic

more: http://learn.knockoutjs.com/#/?tutorial=intro

July 18, 2012 Posted by | Uncategorized | , | Leave a comment

MVC in Javascript

http://www.alexatnet.com/articles/model-view-controller-mvc-javascript

Controller:

  • add an item
  • delete an item
  • update

View

  • wired to listen for add button click, invokes controller
  • wired to listen for delete button click, invokes controller
  • Event (model) handler for itemAdded, itemRemoved
  • sender object
  • attach method to add handler to the event
  • notify method to invoke a handlers

Model

  •  list of current items
  • selected index
  • define Event (model) for item added, removed, selectedindex changed
  • model getters/setter methods for items

July 17, 2012 Posted by | Uncategorized | | Leave a comment

From Sencha to jQuery

After learning alot about EXTJS, it makes sense to get familiar with jQuery. If you have 15 minutes, this is a good overview. Similarly, try this slide share too as it provides good explanations.  As well, there is a jQuery fundamentals, an  online book or  jQuery in Action. As the first chapter says :

If you’ve spent any time at all trying to add dynamic functionality to your pages, you’ve found that you’re constantly following a pattern of selecting an element or group of elements and operating upon those elements in some fashion. You could be hiding or revealing the elements, adding a CSS class to them, animating them, or modifying their attributes.

This javascript library make it easier to accomplish these routine blocks of code in your client code.
To collect a group of elements, we use the simple syntax:

$(selector)
or
jQuery(selector)

The $ () function (an alias for the jQuery() function)  returns a special javascript object containing an array of DOM elements (known as the wrapped set or wrapper)  that match the selector.

Then, jQuery provides methods (or sometimes known as commands or actions) that can act on the group of elements. Some of these actions when completed return the same set of elements that can then again be acted on (known as chaining).

jQuery. or $. is the notation for utility functions.

15 days of jQuery

Selectors

Dimensions

Traversing

Maniplulation

Utilities

Events , Event Object

Ajax

July 14, 2012 Posted by | Uncategorized | , | 1 Comment

EXTJS Linkage

Over the course of doing some EXTJS4 development, I have come across some good sites that will be good reference for knowledge.

EXJS4 Training Video

Fusion Cube on EXTJS

DashasSalo on Sencha

Dconstructing Javascript 

20-things-to-avoid-or-do-when-getting-started-with-extjs-and-sencha-touch

Missing CSS for Breadcrumbs [more]

Designing web interfaces

Sencha examples

http://www.sencha.com/conference/session/ext-js-4-advanced-expert-techniques

http://www.slideshare.net/senchainc/ext-js-41-layouts-performance-and-api-updates

http://existdissolve.com/2012/02/extjs-4-querying-records-in-a-data-store/

http://www.famfamfam.com/lab/icons/

http://www.diloc.de/blog/2011/05/05/extjs4-form-validation-via-model-binding/

http://blog.falafel.com/blogs/basememara/11-12-15/Building_a_Mobile_Web_App_using_Sencha_Touch_2_and_MVC

In the Folds

April 25, 2012 Posted by | Web/Tech | | Leave a comment

EXTJS4 Tree

I am designing a Tree for use in the EXTJS4.  In my tree I will be adding new nodes to the Tree. The basic Sencha Tree example is quite the simple case.

The tree I am defining makes use of the Tree Panel as follows:

Ext.define(‘my.view.FolderList’, {
extend : ‘Ext.tree.Panel’

Just like the example, I define my first column as a ‘tree column’:

xtype: ‘treecolumn’, //this is so we know which column will show the tree

Some methods of the Tree Panel which will be usefull:

Via the getSelectionModel()  which returns Ext.selection.Model , you can get:

http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.NodeInterface-method-expand

http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.NodeInterface-cfg-expanded

http://docs.sencha.com/ext-js/4-0/#!/api/Ext.tree.Panel-method-expandPath

http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.NodeInterface-method-getPath

http://www.clintharris.net/2011/how-to-use-extjs-4-treepanels-with-both-static-data-and-model-stores/

http://stackoverflow.com/questions/7491638/extjs-4-treestore-with-both-static-and-dynamically-loaded-data

http://www.sencha.com/forum/showthread.php?179514-Dynamic-node-loading-TreeStore-Panel

http://www.mysamplecode.com/2012/03/extjs-4-reload-tree-node-error.html

http://www.mindfiresolutions.com/Dynamic-Tree-in-Extjs402-1274.php”>http://www.mindfiresolutions.com/Dynamic-Tree-in-Extjs402-1274.php

April 17, 2012 Posted by | Uncategorized | | Leave a comment

MVC and more with extjs

Every framework/toolkit has their example app. GWT has its Stockwatcher. The Sencha EXTJS  toolkit has the Pandora.

After downloading the code for this, it doesn’t work out of the box until you add the following line of code to app.js:

Ext.Loader.setConfig({enabled:true});

The app.js file defines yout stores, controllers, and

Ext.application({name: ‘Pandora’,

autoCreateViewport: true,

models: [‘Station’, ‘Song’],
stores: [‘Stations’, ‘RecentSongs’, ‘SearchResults’],
controllers: [‘Station’, ‘Song’]
});

Lets start by looking at ViewPort file in view package:

Ext.define(‘Pandora.view.Viewport’, {
extend: ‘Ext.container.Viewport’,
layout: ‘fit’,

It uses the dock item – Any components may be docked to any side of a panel via the new dockedItems config property, and docked items must be configured with a dock property to specify which border to dock to. This allows for amazingly flexible Panel layouts now :

initComponent: function() {
this.items = {
dockedItems: [{
dock: ‘top’,
xtype: ‘toolbar’,
height: 80,
items: [{
xtype: ‘newstation’,
width: 150
}, {
xtype: ‘songcontrols’,
flex: 1
}, {
xtype: ‘component’,
html: ‘Pandora<br>Internet Radio’
}]
}],

From left to right,

layout: {
type: ‘hbox’,
align: ‘stretch’
},

The station list and ad  is in west region,

items: [{
width: 250,
xtype: ‘panel’,
id: ‘west-region’,
layout: {
type: ‘vbox’,
align: ‘stretch’
},
items: [{
xtype: ‘stationslist’,
flex: 1
}, {
html: ‘Ad’,
height: 250,
xtype: ‘panel’
}]

followed by the container in middle:

xtype: ‘container’,
flex: 1,
layout: {
type: ‘vbox’,
align: ‘stretch’
},
items: [{
xtype: ‘recentlyplayedscroller’,
height: 250
}, {
xtype: ‘songinfo’,
flex: 1
}]

Select a station, Station.js has:

stationslist’: {
selectionchange: this.onStationSelect

onStationSelect: function(selModel, selection) {
// Fire an application wide event
this.application.fireEvent(‘stationstart’, selection[0]);
},

In Song.js, wired up for the event as follows:

// Listen for an application wide event
this.application.on({
stationstart: this.onStationStart,
scope: this
});

Thus calls onStationStart which uses store to do a proxy call, but has call back to OnRecentSongsLoad:

onStationStart: function(station) {
var store = this.getRecentSongsStore();
store.load({
callback: this.onRecentSongsLoad,
params: {
station: station.get(‘id’)
},
scope: this
});
},

Next, we go into call back after proxy call:

onRecentSongsLoad: function(songs, request) {
var store = this.getRecentSongsStore(),
selModel = this.getRecentlyPlayedScroller().getSelectionModel();
// The data should already be filtered on the serverside but since we
// are loading static data we need to do this after we loaded all the data
store.clearFilter();
store.filter(‘station’, request.params.station);
store.sort(‘played_date’, ‘ASC’);
selModel.select(store.last());
},

It hits the selModel.select which selModel is equivalent to

this.getRecentlyPlayedScroller().getSelectionModel().select();

We have an event in Song.js that says invoke OnSelect method:

 this.control({
‘recentlyplayedscroller’: {
selectionchange: this.onSongSelect
}
});

In OnSelect method in Song.js tells us to go update SongInfo:

 onSongSelect: function(selModel, selection) {
this.getSongInfo().update(selection[0]);
}

SongInfo update method:

update: function(record) {
var data = record ? record.data : {};
this.down(‘#songdescription’).update(data);
this.callParent([data]);
}

However, this MVC  app example  for mobile Sencha is great.

Create your first EXTJS Object

What is a Store  along with a Store/Proxy –

Model with a validator

Model grid example

http://www.learnsomethings.com/

http://blog.hao909.com/extjs4-viewport-example/

http://www.extjsframework.com/mvc/simple-mvc-application

http://www.fusioncube.net/index.php/extjs4-capturing-window-header-close-button-click

http://as400samplecode.blogspot.com/2011/12/extjs-4-mvc-architecture-tutorial-using_8986.html

http://as400samplecode.blogspot.com/2011/12/extjs-4-mvc-architecture-tutorial-using_878.html

http://as400samplecode.blogspot.com/2011/12/extjs-4-mvc-architecture-tutorial-using_415.html

Ext.AJAX

Reference your view anywhere in MVC

Revisit MVC

Treegrid in EXTJS

Tooltips

Sample, Sample

March 30, 2012 Posted by | Uncategorized | | Leave a comment