vendor/assets/javascripts/emerson/sink.js in emerson-0.0.7 vs vendor/assets/javascripts/emerson/sink.js in emerson-0.0.8
- old
+ new
@@ -43,54 +43,93 @@
// the resultant nodes.
//
// Pass an `override` argument to target a specific sink, say:
//
// data-sink="modal"
+ //
+ // Strategies:
+ //
+ // * `replace` (default)
+ // * `inner`
+ // * `prepend`
+ // * `append`
+ // * `before`
+ // * `after`
+ //
+ // data-sink"modal:inner"
+ //
$.fn.sink = function(override) {
_.each(this, function(e) {
- var elem = $(e);
- var key = override || elem.data('sink');
- var selector, matches;
+ var element = $(e);
+ var key = override || element.data('sink');
+ var selector, matches, count;
if(key) {
- selector = '[data-sink="' + key + '"]';
+ selector = '[data-sink^="' + key + '"]';
matches = $(selector);
+ count = matches.length;
- if(matches.length > 1) {
- matches.each(function() {
- var replacement = prepare(elem.clone(true));
-
- $(this)
- .trigger('sink:before')
- .replaceWith(replacement);
-
- replacement.trigger('sink:after');
- });
+ if(count) {
+ process(element, matches);
}
- else {
- matches.trigger('sink:before');
- prepare(elem)
- .replaceAll(matches)
- .trigger('sink:after');
- }
}
});
return this;
};
// Internal Implementation
// --------------------------------------------------------------------------
+ var strategies = {
+ replace : $.fn.replaceAll,
+ inner : function(target) {
+ target.empty();
+ return this.appendTo(target);
+ },
+ prepend : $.fn.prependTo,
+ append : $.fn.appendTo,
+ before : $.fn.insertBefore,
+ after : $.fn.insertAfter
+ };
+
// ### prepare
// Clone the replacement source and, if Emerson.view is defined, apply that.
function prepare(source) {
var result = source;
if(Emerson.view) {
result.view();
}
return result;
+ }
+
+ // ### process
+ // ...
+ function process(element, matches) {
+ var parts, strategy, clone;
+
+ if(matches.length > 1) {
+ matches.each(function() {
+ clone = prepare(element.clone(true));
+ parts = $(this).data('sink').split(':');
+ strategy = parts[1] || 'replace';
+
+ $(this).trigger('sink:before');
+ strategies[strategy].call(clone, $(this))
+ .trigger('sink:after');
+
+ clone.trigger('sink:after');
+ });
+ }
+ else {
+ parts = matches.data('sink').split(':');
+ strategy = parts[1] || 'replace';
+
+ matches.trigger('sink:before');
+ strategies[strategy].call(prepare(element), matches)
+ .trigger('sink:after');
+ }
}
})(Emerson);