-
-
Save makenosound/10436610 to your computer and use it in GitHub Desktop.
Viewloader rewrite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
})); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div data-view-foo="bar" data-view-bar='{"bar":"baz"}'/> | |
<div data-view-bar='{"bar":"foo"}'/> | |
<div data-view-foo-bar='{"fooBar":true}'/> |
@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]");
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
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? (Ourviews
on the marketplaces has about 50 at the moment)