2 * Copyright 2010-2013 Ben Birch
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this software except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 var ux = app.ns("ux");
20 ux.Observable = ux.Class.extend((function() {
24 for( var opt in this.config ) { // automatically install observers that are defined in the configuration
25 if( opt.indexOf( 'on' ) === 0 ) {
26 this.on( opt.substring(2) , this.config[ opt ] );
30 _getObs: function( type ) {
31 return ( this.observers[ type.toLowerCase() ] || ( this.observers[ type.toLowerCase() ] = [] ) );
33 on: function( type, fn, params, thisp ) {
34 this._getObs( type ).push( { "cb" : fn, "args" : params || [] , "cx" : thisp || this } );
37 fire: function( type ) {
38 var params = Array.prototype.slice.call( arguments, 1 );
39 this._getObs( type ).slice().forEach( function( ob ) {
40 ob["cb"].apply( ob["cx"], ob["args"].concat( params ) );
44 removeAllObservers: function() {
47 removeObserver: function( type, fn ) {
48 var obs = this._getObs( type ),
49 index = obs.reduce( function(p, t, i) { return (t.cb === fn) ? i : p; }, -1 );
51 obs.splice( index, 1 );
53 return this; // make observable functions chainable
55 hasObserver: function( type ) {
56 return !! this._getObs( type ).length;