Created
October 6, 2015 18:39
-
-
Save monoblaine/2aeb84b316bb9282bdc1 to your computer and use it in GitHub Desktop.
Ractive JS - Progressive Enhancement (sort of)
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 ($) { "use strict"; | |
var templates = {}; | |
// cfg.consumerName {String} (if undefined, templateId is used instead) | |
// cfg.templateId {String} (required) | |
function makeItRactive (el, cfg) { | |
var $el = $(el), | |
options = $.extend(true, {}, $el.data(), typeof cfg === "object" && cfg), | |
data = {}, | |
templateId = options.templateId, | |
templateInfo, template, bindingName, partialName, ractiveCfg, $input; | |
if ((templateInfo = templates[templateId]) === undefined) { | |
templateInfo = cacheTemplate(templateId); | |
} | |
partialName = templateInfo.partialName; | |
template = templateInfo.template; | |
$el.find('[data-binding-name]').each(function () { | |
bindingName = ($input = $(this)).data("binding-name"); | |
if ($input.is(":checkbox")) { | |
data[bindingName] = $input.is(":checked"); | |
$input.attr("data-ractivable-checked", "{{" + bindingName + "}}" ).attr("checked", null); | |
} | |
else if ($input.is(":radio")) { | |
// TODO: should be adjusted to radio inputs as well | |
throw "not implemented"; | |
} | |
else if ($input.is(":input")) { | |
data[bindingName] = $input.val(); | |
$input.attr("data-ractivable-value", "{{" + bindingName + "}}" ).attr("value", null); | |
} | |
else { | |
throw "not supported"; | |
} | |
}); | |
ractiveCfg = { | |
el : $el, | |
$el : $el, | |
data : data, | |
noIntro : true, | |
template : partialName === undefined ? template : createCompoundTemplate(template, partialName, $el.html().replace(/data\-ractivable\-/g, "")) | |
}; | |
new Ractive($.extend(true, ractiveCfg, $.fn.ractivable.consumers[options.consumerName || templateId]())); | |
} | |
function cacheTemplate (templateId) { | |
var $script = $("#" + templateId), | |
template = { | |
partialName : $script.data("partial-name"), | |
template : $script.text() | |
}; | |
templates[templateId] = template; | |
return template; | |
} | |
function createCompoundTemplate (template, partialName, partialSource) { | |
return template + "\n" + "{{#partial " + partialName + "}}" + partialSource + "{{/partial}}"; | |
} | |
$.fn.ractivable = function (cfg) { | |
return this.each(function () { makeItRactive(this, cfg); }); | |
}; | |
$.fn.ractivable.consumers = {}; | |
$(function () { | |
$('[data-role="ractivable"]').ractivable(); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment