forked from jupiterjs/jquerymx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.js
More file actions
906 lines (871 loc) · 28.4 KB
/
controller.js
File metadata and controls
906 lines (871 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
steal.plugins('jquery/class', 'jquery/lang', 'jquery/event/destroyed').then(function( $ ) {
// ------- helpers ------
// Binds an element, returns a function that unbinds
var bind = function( el, ev, callback ) {
var wrappedCallback,
binder = el.bind && el.unbind ? el : $(isFunction(el) ? [el] : el);
//this is for events like >click.
if ( ev.indexOf(">") === 0 ) {
ev = ev.substr(1);
wrappedCallback = function( event ) {
if ( event.target === el ) {
callback.apply(this, arguments);
}
};
}
binder.bind(ev, wrappedCallback || callback);
// if ev name has >, change the name and bind
// in the wrapped callback, check that the element matches the actual element
return function() {
binder.unbind(ev, wrappedCallback || callback);
el = ev = callback = wrappedCallback = null;
};
},
makeArray = $.makeArray,
isArray = $.isArray,
isFunction = $.isFunction,
extend = $.extend,
Str = $.String,
// Binds an element, returns a function that unbinds
delegate = function( el, selector, ev, callback ) {
var binder = el.delegate && el.undelegate ? el : $(isFunction(el) ? [el] : el)
binder.delegate(selector, ev, callback);
return function() {
binder.undelegate(selector, ev, callback);
binder = el = ev = callback = selector = null;
};
},
binder = function( el, ev, callback, selector ) {
return selector ? delegate(el, selector, ev, callback) : bind(el, ev, callback);
},
/**
* moves 'this' to the first argument
*/
shifter = function shifter(cb) {
return function() {
return cb.apply(null, [this.nodeName ? $(this) : this].concat(Array.prototype.slice.call(arguments, 0)));
};
},
// matches dots
dotsReg = /\./g,
// matches controller
controllersReg = /_?controllers?/ig,
//used to remove the controller from the name
underscoreAndRemoveController = function( className ) {
return Str.underscore(className.replace("jQuery.", "").replace(dotsReg, '_').replace(controllersReg, ""));
},
// checks if it looks like an action
actionMatcher = /[^\w]/,
// handles parameterized action names
parameterReplacer = /\{([^\}]+)\}/g,
breaker = /^(?:(.*?)\s)?([\w\.\:>]+)$/,
basicProcessor,
data = function(el, data){
return $.data(el, "controllers", data)
};
/**
* @class jQuery.Controller
* @tag core
* @plugin jquery/controller
* @download http://jmvcsite.heroku.com/pluginify?plugins[]=jquery/controller/controller.js
* @test jquery/controller/qunit.html
*
* Controllers organize event handlers using event delegation.
* If something happens in your application (a user click or a [jQuery.Model|Model] instance being updated),
* a controller should respond to it.
*
* Controllers make your code deterministic, reusable, organized and can tear themselves
* down auto-magically. Read about [http://jupiterjs.com/news/writing-the-perfect-jquery-plugin
* the theory behind controller] and
* a [http://jupiterjs.com/news/organize-jquery-widgets-with-jquery-controller walkthrough of its features]
* on Jupiter's blog.
*
*
* ## Basic Example
*
* Instead of
*
* @codestart
* $(function(){
* $('#tabs').click(someCallbackFunction1)
* $('#tabs .tab').click(someCallbackFunction2)
* $('#tabs .delete click').click(someCallbackFunction3)
* });
* @codeend
*
* do this
*
* @codestart
* $.Controller('Tabs',{
* click: function() {...},
* '.tab click' : function() {...},
* '.delete click' : function() {...}
* })
* $('#tabs').tabs();
* @codeend
*
* ## Tabs Example
*
* @demo jquery/controller/controller.html
*
*
* ## Using Controller
*
* Controller helps you build and organize jQuery plugins. It can be used
* to build simple widgets, like a slider, or organize multiple
* widgets into something greater.
*
* To understand how to use Controller, you need to understand
* the typical lifecycle of a jQuery widget and how that maps to
* controller's functionality:
*
* ### A controller class is created.
*
* $.Controller("MyWidget",
* {
* defaults : {
* message : "Remove Me"
* }
* },
* {
* init : function(rawEl, rawOptions){
* this.element.append(
* "<div>"+this.options.message+"</div>"
* );
* },
* "div click" : function(div, ev){
* div.remove();
* }
* })
*
* This creates a <code>$.fn.my_widget</code> [jquery.controller.plugin jQuery helper function]
* that can be used to create a new controller instance on an element.
*
* ### An instance of controller is created on an element
*
* $('.thing').my_widget(options) // calls new MyWidget(el, options)
*
* This calls <code>new MyWidget(el, options)</code> on
* each <code>'.thing'</code> element.
*
* When a new [jQuery.Class Class] instance is created, it calls the class's
* prototype setup and init methods. Controller's [jQuery.Controller.prototype.setup setup]
* method:
*
* - Sets [jQuery.Controller.prototype.element this.element] and adds the controller's name to element's className.
* - Merges passed in options with defaults object and sets it as [jQuery.Controller.prototype.options this.options]
* - Saves a reference to the controller in <code>$.data</code>.
* - [jquery.controller.listening Binds all event handler methods].
*
*
* ### The controller responds to events
*
* Typically, Controller event handlers are automatically bound. However, there are
* multiple ways to [jquery.controller.listening listen to events] with a controller.
*
* Once an event does happen, the callback function is always called with 'this'
* referencing the controller instance. This makes it easy to use helper functions and
* save state on the controller.
*
*
* ### The widget is destroyed
*
* If the element is removed from the page, the
* controller's [jQuery.Controller.prototype.destroy] method is called.
* This is a great place to put any additional teardown functionality.
*
* You can also teardown a controller programatically like:
*
* $('.thing').my_widget('destroy');
*
* ## Todos Example
*
* Lets look at a very basic example -
* a list of todos and a button you want to click to create a new todo.
* Your HTML might look like:
*
* @codestart html
* <div id='todos'>
* <ol>
* <li class="todo">Laundry</li>
* <li class="todo">Dishes</li>
* <li class="todo">Walk Dog</li>
* </ol>
* <a class="create">Create</a>
* </div>
* @codeend
*
* To add a mousover effect and create todos, your controller might look like:
*
* @codestart
* $.Controller.extend('Todos',{
* ".todo mouseover" : function( el, ev ) {
* el.css("backgroundColor","red")
* },
* ".todo mouseout" : function( el, ev ) {
* el.css("backgroundColor","")
* },
* ".create click" : function() {
* this.find("ol").append("<li class='todo'>New Todo</li>");
* }
* })
* @codeend
*
* Now that you've created the controller class, you've must attach the event handlers on the '#todos' div by
* creating [jQuery.Controller.prototype.setup|a new controller instance]. There are 2 ways of doing this.
*
* @codestart
* //1. Create a new controller directly:
* new Todos($('#todos'));
* //2. Use jQuery function
* $('#todos').todos();
* @codeend
*
* ## Controller Initialization
*
* It can be extremely useful to add an init method with
* setup functionality for your widget.
*
* In the following example, I create a controller that when created, will put a message as the content of the element:
*
* @codestart
* $.Controller.extend("SpecialController",
* {
* init: function( el, message ) {
* this.element.html(message)
* }
* })
* $(".special").special("Hello World")
* @codeend
*
* ## Removing Controllers
*
* Controller removal is built into jQuery. So to remove a controller, you just have to remove its element:
*
* @codestart
* $(".special_controller").remove()
* $("#containsControllers").html("")
* @codeend
*
* It's important to note that if you use raw DOM methods (<code>innerHTML, removeChild</code>), the controllers won't be destroyed.
*
* If you just want to remove controller functionality, call destroy on the controller instance:
*
* @codestart
* $(".special_controller").controller().destroy()
* @codeend
*
* ## Accessing Controllers
*
* Often you need to get a reference to a controller, there are a few ways of doing that. For the
* following example, we assume there are 2 elements with <code>className="special"</code>.
*
* @codestart
* //creates 2 foo controllers
* $(".special").foo()
*
* //creates 2 bar controllers
* $(".special").bar()
*
* //gets all controllers on all elements:
* $(".special").controllers() //-> [foo, bar, foo, bar]
*
* //gets only foo controllers
* $(".special").controllers(FooController) //-> [foo, foo]
*
* //gets all bar controllers
* $(".special").controllers(BarController) //-> [bar, bar]
*
* //gets first controller
* $(".special").controller() //-> foo
*
* //gets foo controller via data
* $(".special").data("controllers")["FooController"] //-> foo
* @codeend
*
* ## Calling methods on Controllers
*
* Once you have a reference to an element, you can call methods on it. However, Controller has
* a few shortcuts:
*
* @codestart
* //creates foo controller
* $(".special").foo({name: "value"})
*
* //calls FooController.prototype.update
* $(".special").foo({name: "value2"})
*
* //calls FooController.prototype.bar
* $(".special").foo("bar","something I want to pass")
* @codeend
*/
$.Class("jQuery.Controller",
/**
* @Static
*/
{
/**
* Does 3 things:
* <ol>
* <li>Creates a jQuery helper for this controller.</li>
* <li>Calculates and caches which functions listen for events.</li>
* <li> and attaches this element to the documentElement if onDocument is true.</li>
* </ol>
* <h3>jQuery Helper Naming Examples</h3>
* @codestart
* "TaskController" -> $().task_controller()
* "Controllers.Task" -> $().controllers_task()
* @codeend
*/
init: function() {
// if you didn't provide a name, or are controller, don't do anything
if (!this.shortName || this.fullName == "jQuery.Controller" ) {
return;
}
// cache the underscored names
this._fullName = underscoreAndRemoveController(this.fullName);
this._shortName = underscoreAndRemoveController(this.shortName);
var controller = this,
pluginname = this.pluginName || this._fullName,
funcName, forLint;
// create jQuery plugin
if (!$.fn[pluginname] ) {
$.fn[pluginname] = function( options ) {
var args = makeArray(arguments),
//if the arg is a method on this controller
isMethod = typeof options == "string" && isFunction(controller.prototype[options]),
meth = args[0];
return this.each(function() {
//check if created
var controllers = data(this),
//plugin is actually the controller instance
plugin = controllers && controllers[pluginname];
if ( plugin ) {
if ( isMethod ) {
// call a method on the controller with the remaining args
plugin[meth].apply(plugin, args.slice(1));
} else {
// call the plugin's update method
plugin.update.apply(plugin, args);
}
} else {
//create a new controller instance
controller.newInstance.apply(controller, [this].concat(args));
}
});
};
}
// make sure listensTo is an array
//@steal-remove-start
if (!isArray(this.listensTo) ) {
throw "listensTo is not an array in " + this.fullName;
}
//@steal-remove-end
// calculate and cache actions
this.actions = {};
for ( funcName in this.prototype ) {
if (funcName == 'constructor' || !isFunction(this.prototype[funcName]) ) {
continue;
}
if ( this._isAction(funcName) ) {
this.actions[funcName] = this._action(funcName);
}
}
/**
* @attribute onDocument
* Set to true if you want to automatically attach this element to the documentElement.
*/
if ( this.onDocument ) {
forLint = new controller(document.documentElement);
}
},
hookup: function( el ) {
return new this(el);
},
/**
* @hide
* @param {String} methodName a prototype function
* @return {Boolean} truthy if an action or not
*/
_isAction: function( methodName ) {
if ( actionMatcher.test(methodName) ) {
return true;
} else {
return $.inArray(methodName, this.listensTo) > -1 || $.event.special[methodName] || processors[methodName];
}
},
/**
* @hide
* @param {Object} methodName the method that will be bound
* @param {Object} [options] first param merged with class default options
* @return {Object} null or the processor and pre-split parts.
* The processor is what does the binding/subscribing.
*/
_action: function( methodName, options ) {
//if we don't have a controller instance, we'll break this guy up later
parameterReplacer.lastIndex = 0;
if (!options && parameterReplacer.test(methodName) ) {
return null;
}
var convertedName = options ? Str.sub(methodName, [options, window]) : methodName,
arr = isArray(convertedName),
parts = (arr ? convertedName[1] : convertedName).match(breaker),
event = parts[2],
processor = processors[event] || basicProcessor;
return {
processor: processor,
parts: parts,
delegate : arr ? convertedName[0] : undefined
};
},
/**
* @attribute processors
* An object of {eventName : function} pairs that Controller uses to hook up events
* auto-magically. A processor function looks like:
*
* jQuery.Controller.processors.
* myprocessor = function( el, event, selector, cb, controller ) {
* //el - the controller's element
* //event - the event (myprocessor)
* //selector - the left of the selector
* //cb - the function to call
* //controller - the binding controller
* };
*
* This would bind anything like: "foo~3242 myprocessor".
*
* The processor must return a function that when called,
* unbinds the event handler.
*
* Controller already has processors for the following events:
*
* - change
* - click
* - contextmenu
* - dblclick
* - focusin
* - focusout
* - keydown
* - keyup
* - keypress
* - mousedown
* - mouseenter
* - mouseleave
* - mousemove
* - mouseout
* - mouseover
* - mouseup
* - reset
* - resize
* - scroll
* - select
* - submit
*
* The following processors always listen on the window or document:
*
* - windowresize
* - windowscroll
* - load
* - unload
* - hashchange
* - ready
*
* Which means anytime the window is resized, the following controller will listen to it:
*
* $.Controller('Sized',{
* windowresize : function(){
* this.element.width(this.element.parent().width() / 2);
* }
* });
*
* $('.foo').sized();
*/
processors: {},
/**
* @attribute listensTo
* A list of special events this controller listens too. You only need to add event names that
* are whole words (ie have no special characters).
*
* $.Controller('TabPanel',{
* listensTo : ['show']
* },{
* 'show' : function(){
* this.element.show();
* }
* })
*
* $('.foo').tab_panel().trigger("show");
*/
listensTo: [],
/**
* @attribute defaults
* A object of name-value pairs that act as default values for a controller's
* [jQuery.Controller.prototype.options options].
*
* $.Controller("Message",
* {
* defaults : {
* message : "Hello World"
* }
* },{
* init : function(){
* this.element.text(this.options.message);
* }
* })
*
* $("#el1").message(); //writes "Hello World"
* $("#el12").message({message: "hi"}); //writes hi
*/
defaults: {}
},
/**
* @Prototype
*/
{
/**
* Setup is where most of controller's magic happens. It does the following:
*
* ### Sets this.element
*
* The first parameter passed to new Controller(el, options) is expected to be
* an element. This gets converted to a jQuery wrapped element and set as
* [jQuery.Controller.prototype.element this.element].
*
* ### Adds the controller's name to the element's className.
*
* Controller adds it's plugin name to the element's className for easier
* debugging. For example, if your Controller is named "Foo.Bar", it adds
* "foo_bar" to the className.
*
* ### Saves the controller in $.data
*
* A reference to the controller instance is saved in $.data. You can find
* instances of "Foo.Bar" like:
*
* $("#el").data("controllers")['foo_bar'].
*
* ### Binds event handlers
*
* Setup does the event binding described in [jquery.controller.listening Listening To Events].
*
* ## API
* @param {HTMLElement} element the element this instance operates on.
* @param {Object} [options] option values for the controller. These get added to
* this.options.
*/
setup: function( element, options ) {
var funcName, ready, cls = this.Class;
//want the raw element here
element = element.jquery ? element[0] : element;
//set element and className on element
this.element = $(element).addClass(cls._fullName);
//set in data
(data(element) || data(element, {}))[cls._fullName] = this;
//adds bindings
this._bindings = [];
/**
* @attribute options
* Options is [jQuery.Controller.static.defaults] merged with the 2nd argument
* passed to a controller (or the first argument passed to the
* [jquery.controller.plugin controller's jQuery plugin]).
*
* For example:
*
* $.Controller("Tabs",
* {
* defaults : {
* activeClass: "ui-active-state"
* }
* },
* {
* init : function(){
* this.element.addClass(this.options.activeClass);
* }
* })
*
* $("#tabs1").tabs() // adds 'ui-active-state'
* $("#tabs2").tabs({activeClass : 'active'}) // adds 'active'
*
*
*/
this.options = extend( extend(true, {}, cls.defaults), options);
//go through the cached list of actions and use the processor to bind
for ( funcName in cls.actions ) {
if ( cls.actions.hasOwnProperty(funcName) ) {
ready = cls.actions[funcName] || cls._action(funcName, this.options);
this._bindings.push(
ready.processor(ready.delegate || element, ready.parts[2], ready.parts[1], this.callback(funcName), this));
}
}
/**
* @attribute called
* String name of current function being called on controller instance. This is
* used for picking the right view in render.
* @hide
*/
this.called = "init";
//setup to be destroyed ... don't bind b/c we don't want to remove it
//this.element.bind('destroyed', this.callback('destroy'))
var destroyCB = shifter(this.callback("destroy"));
this.element.bind("destroyed", destroyCB);
this._bindings.push(function( el ) {
//destroyCB.removed = true;
$(element).unbind("destroyed", destroyCB);
});
/**
* @attribute element
* The controller instance's delegated element. This
* is set by [jQuery.Controller.prototype.setup setup]. It
* is a jQuery wrapped element.
*
* For example, if I add MyWidget to a '#myelement' element like:
*
* $.Controller("MyWidget",{
* init : function(){
* this.element.css("color","red")
* }
* })
*
* $("#myelement").my_widget()
*
* MyWidget will turn #myelement's font color red.
*
* ## Using a different element.
*
* Sometimes, you want a different element to be this.element. A
* very common example is making progressively enhanced form widgets.
*
* To change this.element, overwrite Controller's setup method like:
*
* $.Controller("Combobox",{
* setup : function(el, options){
* this.oldElement = $(el);
* var newEl = $('<div/>');
* this.oldElement.wrap(newEl);
* this._super(newEl, options);
* },
* init : function(){
* this.element //-> the div
* },
* ".option click" : function(){
* // event handler bound on the div
* },
* destroy : function(){
* var div = this.element; //save reference
* this._super();
* div.replaceWith(this.oldElement);
* }
* }
*/
return this.element;
},
/**
* Bind attaches event handlers that will be removed when the controller is removed.
* This is a good way to attach to an element not in the controller's element.
* <br/>
* <h3>Examples:</h3>
* @codestart
* init: function() {
* // calls somethingClicked(el,ev)
* this.bind('click','somethingClicked')
*
* // calls function when the window is clicked
* this.bind(window, 'click', function(ev){
* //do something
* })
* },
* somethingClicked: function( el, ev ) {
*
* }
* @codeend
* @param {HTMLElement|jQuery.fn} [el=this.element] The element to be bound
* @param {String} eventName The event to listen for.
* @param {Function|String} func A callback function or the String name of a controller function. If a controller
* function name is given, the controller function is called back with the bound element and event as the first
* and second parameter. Otherwise the function is called back like a normal bind.
* @return {Integer} The id of the binding in this._bindings
*/
bind: function( el, eventName, func ) {
if ( typeof el == 'string' ) {
func = eventName;
eventName = el;
el = this.element;
}
return this._binder(el, eventName, func);
},
_binder: function( el, eventName, func, selector ) {
if ( typeof func == 'string' ) {
func = shifter(this.callback(func));
}
this._bindings.push(binder(el, eventName, func, selector));
return this._bindings.length;
},
/**
* Delegate will delegate on an elememt and will be undelegated when the controller is removed.
* This is a good way to delegate on elements not in a controller's element.<br/>
* <h3>Example:</h3>
* @codestart
* // calls function when the any 'a.foo' is clicked.
* this.delegate(document.documentElement,'a.foo', 'click', function(ev){
* //do something
* })
* @codeend
* @param {HTMLElement|jQuery.fn} [element=this.element] the element to delegate from
* @param {String} selector the css selector
* @param {String} eventName the event to bind to
* @param {Function|String} func A callback function or the String name of a controller function. If a controller
* function name is given, the controller function is called back with the bound element and event as the first
* and second parameter. Otherwise the function is called back like a normal bind.
* @return {Integer} The id of the binding in this._bindings
*/
delegate: function( element, selector, eventName, func ) {
if ( typeof element == 'string' ) {
func = eventName;
eventName = selector;
selector = element;
element = this.element;
}
return this._binder(element, eventName, func, selector);
},
/**
* Called if an controller's [jquery.controller.plugin jQuery helper] is called on an element that already has a controller instance
* of the same type. Extends [jQuery.Controller.prototype.options this.options] with the options passed in. If you overwrite this, you might want to call
* this._super.
* <h3>Examples</h3>
* @codestart
* $.Controller.extend("Thing",{
* init: function( el, options ) {
* alert('init')
* },
* update: function( options ) {
* this._super(options);
* alert('update')
* }
* });
* $('#myel').thing(); // alerts init
* $('#myel').thing(); // alerts update
* @codeend
* @param {Object} options
*/
update: function( options ) {
extend(this.options, options);
},
/**
* Destroy unbinds and undelegates all event handlers on this controller,
* and prevents memory leaks. This is called automatically
* if the element is removed. You can overwrite it to add your own
* teardown functionality:
*
* $.Controller("ChangeText",{
* init : function(){
* this.oldText = this.element.text();
* this.element.text("Changed!!!")
* },
* destroy : function(){
* this.element.text(this.oldText);
* this._super(); //Always call this!
* })
*
* You could call destroy manually on an element with ChangeText
* added like:
*
* $("#changed").change_text("destroy");
*
* ### API
*/
destroy: function() {
if ( this._destroyed ) {
throw this.Class.shortName + " controller instance has been deleted";
}
var self = this,
fname = this.Class._fullName,
controllers;
this._destroyed = true;
this.element.removeClass(fname);
$.each(this._bindings, function( key, value ) {
value(self.element[0]);
});
delete this._actions;
delete this.element.data("controllers")[fname];
$(this).triggerHandler("destroyed"); //in case we want to know if the controller is removed
this.element = null;
},
/**
* Queries from the controller's element.
* @codestart
* ".destroy_all click" : function() {
* this.find(".todos").remove();
* }
* @codeend
* @param {String} selector selection string
* @return {jQuery.fn} returns the matched elements
*/
find: function( selector ) {
return this.element.find(selector);
},
//tells callback to set called on this. I hate this.
_set_called: true
});
var processors = $.Controller.processors,
//------------- PROCESSSORS -----------------------------
//processors do the binding. They return a function that
//unbinds when called.
//the basic processor that binds events
basicProcessor = function( el, event, selector, cb, controller ) {
var c = controller.Class;
// document controllers use their name as an ID prefix.
if ( c.onDocument && !/^Main(Controller)?$/.test(c.shortName) && el === controller.element[0]) { //prepend underscore name if necessary
selector = selector ? "#" + c._shortName + " " + selector : "#" + c._shortName;
}
return binder(el, event, shifter(cb), selector);
};
//set commong events to be processed as a basicProcessor
$.each("change click contextmenu dblclick keydown keyup keypress mousedown mousemove mouseout mouseover mouseup reset resize scroll select submit focusin focusout mouseenter mouseleave".split(" "), function( i, v ) {
processors[v] = basicProcessor;
});
/**
* @add jQuery.fn
*/
//used to determine if a controller instance is one of controllers
//controllers can be strings or classes
var i, isAControllerOf = function( instance, controllers ) {
for ( i = 0; i < controllers.length; i++ ) {
if ( typeof controllers[i] == 'string' ? instance.Class._shortName == controllers[i] : instance instanceof controllers[i] ) {
return true;
}
}
return false;
};
/**
* @function controllers
* Gets all controllers in the jQuery element.
* @return {Array} an array of controller instances.
*/
$.fn.controllers = function() {
var controllerNames = makeArray(arguments),
instances = [],
controllers, c, cname;
//check if arguments
this.each(function() {
controllers = $.data(this, "controllers");
for ( cname in controllers ) {
if ( controllers.hasOwnProperty(cname) ) {
c = controllers[cname];
if (!controllerNames.length || isAControllerOf(c, controllerNames) ) {
instances.push(c);
}
}
}
});
return instances;
};
/**
* @function controller
* Gets a controller in the jQuery element. With no arguments, returns the first one found.
* @param {Object} controller (optional) if exists, the first controller instance with this class type will be returned.
* @return {jQuery.Controller} the first controller.
*/
$.fn.controller = function( controller ) {
return this.controllers.apply(this, arguments)[0];
};
});