﻿/// <reference path="./Scripts/typings/handlebars/handlebars.d.ts"/>

interface TemplateViewOptions extends ViewOptions
{
    tmplEl?: any;
}

abstract class TemplateView extends View
{
    // Attributes
    private _template: HandlebarsTemplateDelegate;

    // Constructor
    constructor(parentEl: any, options?: TemplateViewOptions)
    {
        super(parentEl, options);
        if (options && options.tmplEl)
        {
            this.LoadTemplate(options.tmplEl);
        }
    }

    // Properties
    protected get Template(): HandlebarsTemplateDelegate
    {
        return this._template;
    }

    // Methods
    LoadTemplate(tmplEl: any): boolean
    {
        // Load the template from a HTML tag
        // on the web page.
        var $tmplEl: JQuery = this.GetJQueryObject(tmplEl);

        if ($tmplEl.length == 0) return false;

        // Compile the template and store it
        this._template = Handlebars.compile($tmplEl.html());

        this.OnTemplateLoad();
        return true;
    }

    // Child should override this!!
    OnTemplateLoad(): void { }

    HasTemplate(): boolean
    {
        return this._template !== undefined;
    }

    Render(): void
    {
        if (this._template === undefined) throw new Error("No template supplied before rendering ModelView");

        // Render the view
        super.Render();
    }
}  