Skip to content

Instantly share code, notes, and snippets.

@makenosound
Forked from anonymous/app.js
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save makenosound/10436610 to your computer and use it in GitHub Desktop.
Save makenosound/10436610 to your computer and use it in GitHub Desktop.
Viewloader rewrite
var views = {
foo: function($el, el, props) {
console.log(props);
},
bar: function($el, el, props) {
console.log(props);
},
fooBar: function($el, el, props) {
console.log(props);
}
};
viewloader.execute(views);
// -> "bar"
// -> {"bar": "baz"}
// -> {"bar": "foo"}
// -> {"fooBar": true}
(function(root, factory) {
root.viewloader = factory({},(root.jQuery || root.Zepto || root.$)); // Browser global
}(this, function(viewloader,$) {
"use strict";
var re = new RegExp('([a-z])([A-Z])', 'g'),
dasherize = function(s) {
return s.replace(re, '$1-$2').toLowerCase();
};
viewloader.execute = function(views, $scope) {
for(var view in views) {
var dashView = dasherize(view),
selector = "[data-view-" + dashView + "]",
$els = $scope ? $scope.find(selector) : $(selector);
$els.each(function(i, el) {
var $el = $(el);
views[view]($el, el, $el.data("view-" + dashView));
});
};
};
return viewloader;
}));
<div data-view-foo="bar" data-view-bar='{"bar":"baz"}'/>
<div data-view-bar='{"bar":"foo"}'/>
<div data-view-foo-bar='{"fooBar":true}'/>
@bensmithett
Copy link

Awesome! Wonder about the perf impact if you throw it a large views object since it hits the DOM once per view now, rather than just the once before? (Our views on the marketplaces has about 50 at the moment)

@makenosound
Copy link
Author

@bensmitthett Yeah — not exactly sure what the perf difference would be. I don’t imagine in most cases it’d be an issue, but with 50 it might! Will do some tests.

I’m sure we could work out a way to do a single read anyway, just need to work out whether or not that’s actually faster since you’d have to do something like:

$("[data-view-foo],[data-view-bar],[data-view-baz]");

@makenosound
Copy link
Author

Put a basic test up at http://jsperf.com/viewloader-selection. Seems like much of a muchness, faster in some runs, even in most.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment