petermichaux / maria

The MVC framework for JavaScript applications. The real MVC. The Smalltalk MVC. The Gang of Four MVC.
BSD 2-Clause "Simplified" License
764 stars 51 forks source link

Template functions rather than strings ... #74

Closed jamesladd closed 8 years ago

jamesladd commented 10 years ago

If I would rather have a function called to provide my views template string can I simply supply my own getTemplate function in my view?

I'm assuming the mechanism that looks up a variable with the same name as my View will first see if I have a getTemplate function?

petermichaux commented 10 years ago

Your view's getTemplate method is "a function called to provide my views template string". So yes you can override maria.ElementView.prototype.getTemplate.

If you want to do any magic with "convention over configuration" to link your template function to your view then you want to do that by wrapping maria.ElementView.subclass. I don't know exactly what you want to do but something like the following (untested code) might be what you want. You can compare to the maria.ElementView.subclass in Maria that the following wraps around.

maria.ElementView.subclass = (function() {
    var original = maria.ElementView.subclass;
    return function(namespace, name, options) {
        options = options || {};
        var template = options.template;
        var templateName = options.templateName || name.replace(/(View|)$/, 'Template');
        var properties = options.properties || (options.properties = {});

        if (!Object.prototype.hasOwnProperty.call(properties, 'getTemplate')) {
            if (template) {
                properties.getTemplate = function() {
                    return template();
                };
            }
            else if (templateName) {
                properties.getTemplate = function() {
                    /* DEBUG BEGIN */
                    if (!Object.prototype.hasOwnProperty.call(namespace, templateName)) {
                        console.error('Could not find template function named "' + templateName + '".');
                    }
                    /* DEBUG END */
                    return namespace[templateName]();
                };
            }
        }

        return original.call(this, namespace, name, options);
    };
}());
petermichaux commented 8 years ago

I cannot be sure this is a common use case and it seems it is solvable by plugin. The ability to solve problems like this with plugins is what Maria is all about.