All files / lib/module index.js

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985                  25x 25x 25x 25x           25x       25x                                           447x     447x 447x     447x     447x     447x                     25x     447x 447x 447x 447x 447x 447x 447x       447x 447x 447x 447x         447x 447x           447x         447x 8x 8x                       25x 447x   22x     22x 24x 24x 24x                         3x                                 447x                                 25x 295x     295x 295x 295x         295x     295x     295x 295x     295x   294x 294x       294x     294x                                                         25x     107x       106x 6x 6x       100x 100x 100x 100x 100x           100x 22x 22x     100x     14x 14x     14x     100x                   25x 294x     294x     294x     294x   294x                   25x 14x     14x 14x     14x 14x 14x                                 25x                                                         25x 308x   2x 2x   1x                                           25x 604x   62x 62x   5x 4x                                           25x 13x         13x 10x     13x                                 25x 624x     624x 406x 406x                                                           25x 208x       208x               25x 217x 217x           217x     217x 139x         139x 139x 139x 139x 139x             217x                         25x 208x                   25x 217x                       25x 72x         72x   72x 9x 9x 9x 9x 10x             63x       72x     72x   72x                                         25x 74x         74x         73x     73x 73x 73x     73x       73x 72x 49x         73x                                 25x 329x       329x 9x 6x                   329x 55x 55x 55x 55x       329x                                         25x 344x   344x 344x                       344x 249x         344x                   316x     316x       316x       316x       316x     316x             316x     316x                     25x 2x 4x 2x                     25x 203x 203x 131x 131x                         25x 279x 199x 199x 199x 199x     279x                     25x 99x 66x                       25x 90x 90x                             25x 82x 82x                                 25x 65x 65x     65x 2x 2x       65x   65x                     25x 20x 19x 19x 19x     20x                     25x 3x                       25x 24x 24x     24x     24x                           25x 5x 5x     5x 1x     5x 5x 5x 5x 5x       5x   5x       25x 25x 25x 25x     25x         25x   25x    
 
/*jshint browser:true, node:true*/
 
'use strict';
 
/**
 * Module Dependencies
 */
 
var util = require('utils');
var events = require('./events');
var extend = require('extend');
var mixin = util.mixin;
 
/**
 * Exports
 */
 
module.exports = function(fm) {
 
  // Alias prototype for optimum
  // compression via uglifyjs
  var proto = Module.prototype;
 
  /**
   * Module constructor
   *
   * Options:
   *
   *  - `id {String}` a unique id to query by
   *  - `model {Object|Model}` the data with which to associate this module
   *  - `tag {String}` tagName to use for the root element
   *  - `classes {Array}` list of classes to add to the root element
   *  - `template {Function}` a template to use for rendering
   *  - `helpers {Array}`a list of helper function to use on this module
   *  - `children {Object|Array}` list of child modules
   *
   * @constructor
   * @param {Object} options
   * @api public
   */
  function Module(options) {
 
    // Shallow clone the options
    options = mixin({}, options);
 
    // Various config steps
    this._configure(options);
    this._add(options.children);
 
    // Fire before initialize event hook
    this.fireStatic('before initialize', options);
 
    // Run initialize hooks
    if (this.initialize) this.initialize(options);
 
    // Fire initialize event hook
    this.fireStatic('initialize', options);
  }
 
  /**
   * Configures the new Module
   * with the options passed
   * to the constructor.
   *
   * @param  {Object} options
   * @api private
   */
  proto._configure = function(options) {
 
    // Setup static properties
    this._id = options.id || util.uniqueId();
    this._fmid = options.fmid || util.uniqueId('fmid');
    this.tag = options.tag || this.tag || 'div';
    this.classes = options.classes || this.classes || [];
    this.helpers = options.helpers || this.helpers || [];
    this.template = this._setTemplate(options.template || this.template);
    this.slot = options.slot;
 
    // Create id and module
    // lookup objects
    this.children = [];
    this._ids = {};
    this._modules = {};
    this.slots = {};
 
    // Use the model passed in,
    // or create a model from
    // the data passed in.
    var model = options.model || options.data || {};
    this.model = util.isPlainObject(model)
      ? new this.Model(model)
      : model;
 
    // Attach helpers
    // TODO: Fix this for non-ES5 environments
    this.helpers.forEach(this.attachHelper, this);
 
    // We fire and 'inflation' event here
    // so that helpers can make some changes
    // to the view before instantiation.
    if (options.fmid) {
      fm.fire('inflation', this, options);
      this.fireStatic('inflation', options);
    }
  };
 
  /**
   * A private add method
   * that accepts a list of
   * children.
   *
   * @param {Object|Array} children
   * @api private
   */
  proto._add = function(children) {
    if (!children) return;
 
    var isArray = util.isArray(children);
    var child;
 
    for (var key in children) {
      child = children[key];
      if (!isArray) child.slot = key;
      this.add(child);
    }
  },
 
  /**
   * Instantiates the given
   * helper on the Module.
   *
   * @param  {Function} helper
   * @return {Module}
   * @api private
   */
  proto.attachHelper = function(helper) {
    Eif (helper) helper(this);
  },
 
  /**
   * Returns the template function
   * for the view.
   *
   * For template object like Hogan
   * templates with a `render` method
   * we need to bind the context
   * so they can be called without
   * a reciever.
   *
   * @return {Function}
   * @api private
   */
  proto._setTemplate = function(fn) {
    return fn && fn.render
      ? util.bind(fn.render, fn)
      : fn;
  };
 
  /**
   * Adds a child view(s) to another Module.
   *
   * Options:
   *
   *  - `at` The child index at which to insert
   *  - `inject` Injects the child's view element into the parent's
   *  - `slot` The slot at which to insert the child
   *
   * @param {Module|Object} children
   * @param {Object|String|Number} options|slot
   */
  proto.add = function(child, options) {
    Iif (!child) return this;
 
    // Options
    var at = options && options.at;
    var inject = options && options.inject;
    var slot = ('object' === typeof options)
      ? options.slot
      : options;
 
    // Remove this view first if it already has a parent
    if (child.parent) child.remove({ fromDOM: false });
 
    // Assign a slot (prefering defined option)
    slot = child.slot = slot || child.slot;
 
    // Remove any module that already occupies this slot
    var resident = this.slots[slot];
    if (resident) resident.remove({ fromDOM: false });
 
    // If it's not a Module, make it one.
    if (!(child instanceof Module)) child = fm(child);
 
    util.insert(child, this.children, at);
    this._addLookup(child);
 
    // We append the child to the parent view if there is a view
    // element and the users hasn't flagged `append` false.
    Iif (inject) this._injectEl(child.el, options);
 
    // Allow chaining
    return this;
  };
 
  /**
   * Removes a child view from
   * its current Module contexts
   * and also from the DOM unless
   * otherwise stated.
   *
   * Options:
   *
   *  - `fromDOM` Whether the element should be removed from the DOM (default `true`)
   *
   * Example:
   *
   *   // The following are equal
   *   // apple is removed from the
   *   // the view structure and DOM
   *   layout.remove(apple);
   *   apple.remove();
   *
   *   // Apple is removed from the
   *   // view structure, but not the DOM
   *   layout.remove(apple, { el: false });
   *   apple.remove({ el: false });
   *
   * @return {FruitMachine}
   * @api public
   */
  proto.remove = function(param1, param2) {
 
    // Don't do anything if the first arg is undefined
    if (arguments.length === 1 && !param1) return this;
 
    // Allow view.remove(child[, options])
    // and view.remove([options]);
    if (param1 instanceof Module) {
      param1.remove(param2 || {});
      return this;
    }
 
    // Options and aliases
    var options = param1 || {};
    var fromDOM = options.fromDOM !== false;
    var parent = this.parent;
    var el = this.el;
    var parentNode = el && el.parentNode;
    var index;
 
    // Unless stated otherwise,
    // remove the view element
    // from its parent node.
    if (fromDOM && parentNode) {
      parentNode.removeChild(el);
      this._unmount();
    }
 
    if (parent) {
 
      // Remove reference from views array
      index = parent.children.indexOf(this);
      parent.children.splice(index, 1);
 
      // Remove references from the lookup
      parent._removeLookup(this);
    }
 
    return this;
  };
 
  /**
   * Creates a lookup reference for
   * the child view passed.
   *
   * @param {Module} child
   * @api private
   */
  proto._addLookup = function(child) {
    var module = child.module();
 
    // Add a lookup for module
    (this._modules[module] = this._modules[module] || []).push(child);
 
    // Add a lookup for id
    this._ids[child.id()] = child;
 
    // Store a reference by slot
    if (child.slot) this.slots[child.slot] = child;
 
    child.parent = this;
  };
 
  /**
   * Removes the lookup for the
   * the child view passed.
   *
   * @param {Module} child
   * @api private
   */
  proto._removeLookup = function(child) {
    var module = child.module();
 
    // Remove the module lookup
    var index = this._modules[module].indexOf(child);
    this._modules[module].splice(index, 1);
 
    // Remove the id and slot lookup
    delete this._ids[child._id];
    delete this.slots[child.slot];
    delete child.parent;
  };
 
  /**
   * Injects an element into the
   * Module's root element.
   *
   * By default the element is appended.
   *
   * Options:
   *
   *  - `at` The index at which to insert.
   *
   * @param  {Element} el
   * @param  {Object} options
   * @api private
   */
  proto._injectEl = function(el, options) {
    var at = options && options.at;
    var parent = this.el;
    if (!el || !parent) return;
 
    if (typeof at !== 'undefined') {
      parent.insertBefore(el, parent.children[at]);
    } else {
      parent.appendChild(el);
    }
  };
 
  /**
   * Returns a decendent module
   * by id, or if called with no
   * arguments, returns this view's id.
   *
   * Example:
   *
   *   myModule.id();
   *   //=> 'my_view_id'
   *
   *   myModule.id('my_other_views_id');
   *   //=> Module
   *
   * @param  {String|undefined} id
   * @return {Module|String}
   * @api public
   */
  proto.id = function(id) {
    if (!arguments.length) return this._id;
 
    var child = this._ids[id];
    if (child) return child;
 
    return this.each(function(view) {
      return view.id(id);
    });
  };
 
  /**
   * Returns the first descendent
   * Module with the passed module type.
   * If called with no arguments the
   * Module's own module type is returned.
   *
   * Example:
   *
   *   // Assuming 'myModule' has 3 descendent
   *   // views with the module type 'apple'
   *
   *   myModule.modules('apple');
   *   //=> Module
   *
   * @param  {String} key
   * @return {Module}
   */
  proto.module = function(key) {
    if (!arguments.length) return this._module || this.name;
 
    var view = this._modules[key];
    if (view && view.length) return view[0];
 
    return this.each(function(view) {
      return view.module(key);
    });
  };
 
  /**
   * Returns a list of descendent
   * Modules that match the module
   * type given (Similar to
   * Element.querySelectorAll();).
   *
   * Example:
   *
   *   // Assuming 'myModule' has 3 descendent
   *   // views with the module type 'apple'
   *
   *   myModule.modules('apple');
   *   //=> [ Module, Module, Module ]
   *
   * @param  {String} key
   * @return {Array}
   * @api public
   */
  proto.modules = function(key) {
    var list = this._modules[key] || [];
 
    // Then loop each child and run the
    // same opperation, appending the result
    // onto the list.
    this.each(function(view) {
      list = list.concat(view.modules(key));
    });
 
    return list;
  };
 
  /**
   * Calls the passed function
   * for each of the view's
   * children.
   *
   * Example:
   *
   *   myModule.each(function(child) {
   *     // Do stuff with each child view...
   *   });
   *
   * @param  {Function} fn
   * @return {[type]}
   */
  proto.each = function(fn) {
    var l = this.children.length;
    var result;
 
    for (var i = 0; i < l; i++) {
      result = fn(this.children[i]);
      if (result) return result;
    }
  };
 
  /**
   * Templates the view, including
   * any descendent views returning
   * an html string. All data in the
   * views model is made accessible
   * to the template.
   *
   * Child views are printed into the
   * parent template by `id`. Alternatively
   * children can be iterated over a a list
   * and printed with `{{{child}}}}`.
   *
   * Example:
   *
   *   <div class="slot-1">{{{<slot>}}}</div>
   *   <div class="slot-2">{{{<slot>}}}</div>
   *
   *   // or
   *
   *   {{#children}}
   *     {{{child}}}
   *   {{/children}}
   *
   * @return {String}
   * @api public
   */
  proto.toHTML = function() {
    var html = this._innerHTML();
 
    // Wrap the html in a FruitMachine
    // generated root element and return.
    return this._wrapHTML(html);
  };
 
  /**
   * Get the view's innerHTML
   *
   * @return {String}
   */
  proto._innerHTML = function() {
    this.fireStatic('before tohtml');
    var data = {};
    var html;
    var tmp;
 
    // Create an array for view
    // children data needed in template.
    data[fm.config.templateIterator] = [];
 
    // Loop each child
    this.each(function(child) {
      Iif (!child.model) {
        var err = new Error("Child without a model");
        err.context = child;
        throw err;
      }
      tmp = {};
      html = child.toHTML();
      data[child.slot || child.id()] = html;
      tmp[fm.config.templateInstance] = html;
      data.children.push(mixin(tmp, child.model.toJSON()));
    });
 
    // Run the template render method
    // passing children data (for looping
    // or child views) mixed with the
    // view's model data.
    return this.template
      ? this.template(mixin(data, this.model.toJSON()))
      : '';
  };
 
  /**
   * Wraps the module html in
   * a root element.
   *
   * @param  {String} html
   * @return {String}
   * @api private
   */
  proto._wrapHTML = function(html) {
    return '<' + this.tag + ' class="' + this._classes().join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>';
  };
 
  /**
   * Gets a space separated list
   * of all a view's classes
   *
   * @return {String}
   * @api private
   */
  proto._classes = function() {
    return [this.module()].concat(this.classes);
  };
 
  /**
   * Renders the view and replaces
   * the `view.el` with a freshly
   * rendered node.
   *
   * Fires a `render` event on the view.
   *
   * @return {Module}
   */
  proto.render = function() {
    this.fireStatic('before render');
 
    // If possible recycle outer element but
    // build from scratch if there is no
    // existing element or if tag changed
    var el = this.el;
    var classes;
    if (el && el.tagName === this.tag.toUpperCase()) {
      el.innerHTML = this._innerHTML();
      this._unmountChildren();
      classes = el.className.split(/\s+/);
      this._classes().forEach(function(add) {
        if (!~classes.indexOf(add)) el.className = el.className + ' ' + add;
      });
 
    // Sets a new element as a view's
    // root element (purging descendent
    // element caches).
    } else {
      this._setEl(util.toNode(this.toHTML()));
    }
 
    // Fetch all child module elements
    this._fetchEls(this.el);
 
    // Handy hook
    this.fireStatic('render');
 
    return this;
  };
 
  /**
   * Sets up a view and all descendent
   * views.
   *
   * Setup will be aborted if no `view.el`
   * is found. If a view is already setup,
   * teardown is run first to prevent a
   * view being setup twice.
   *
   * Your custom `setup()` method is called
   *
   * Options:
   *
   *  - `shallow` Does not recurse when `true` (default `false`)
   *
   * @param  {Object} options
   * @return {Module}
   */
  proto.setup = function(options) {
    var shallow = options && options.shallow;
 
    // Attempt to fetch the view's
    // root element. Don't continue
    // if no route element is found.
    if (!this._getEl()) return this;
 
    // If this is already setup, call
    // `teardown` first so that we don't
    // duplicate event bindings and shizzle.
    if (this.isSetup) this.teardown({ shallow: true });
 
    // Fire the `setup` event hook
    this.fireStatic('before setup');
    Eif (this._setup) this._setup();
    this.fireStatic('setup');
 
    // Flag view as 'setup'
    this.isSetup = true;
 
    // Call 'setup' on all subviews
    // first (top down recursion)
    if (!shallow) {
      this.each(function(child) {
        child.setup();
      });
    }
 
    // For chaining
    return this;
  };
 
  /**
   * Tearsdown a view and all descendent
   * views that have been setup.
   *
   * Your custom `teardown` method is
   * called and a `teardown` event is fired.
   *
   * Options:
   *
   *  - `shallow` Does not recurse when `true` (default `false`)
   *
   * @param  {Object} options
   * @return {Module}
   */
  proto.teardown = function(options) {
    var shallow = options && options.shallow;
 
    // Call 'setup' on all subviews
    // first (bottom up recursion).
    if (!shallow) {
      this.each(function(child) {
        child.teardown();
      });
    }
 
    // Only teardown if this view
    // has been setup. Teardown
    // is supposed to undo all the
    // work setup does, and therefore
    // will likely run into undefined
    // variables if setup hasn't run.
    if (this.isSetup) {
      this.fireStatic('before teardown');
      Eif (this._teardown) this._teardown();
      this.fireStatic('teardown');
      this.isSetup = false;
    }
 
    // For chaining
    return this;
  };
 
  /**
   * Completely destroys a view. This means
   * a view is torn down, removed from it's
   * current layout context and removed
   * from the DOM.
   *
   * Your custom `destroy` method is
   * called and a `destroy` event is fired.
   *
   * NOTE: `.remove()` is only run on the view
   * that `.destroy()` is directly called on.
   *
   * Options:
   *
   *  - `fromDOM` Whether the view should be removed from DOM (default `true`)
   *
   * @api public
   */
  proto.destroy = function(options) {
    options = options || {};
 
    var remove = options.remove !== false;
    var l = this.children.length;
 
    // Destroy each child view.
    // We don't waste time removing
    // the child elements as they will
    // get removed when the parent
    // element is removed.
    //
    // We can't use the standard Module#each()
    // as the array length gets altered
    // with each iteration, hense the
    // reverse while loop.
    while (l--) {
      this.children[l].destroy({ remove: false });
    }
 
    // Don't continue if this view
    // has already been destroyed.
    if (this.destroyed) return this;
 
    // .remove() is only run on the view that
    // destroy() was called on.
    //
    // It is a waste of time to remove the
    // descendent views as well, as any
    // references to them will get wiped
    // within destroy and they will get
    // removed from the DOM with the main view.
    if (remove) this.remove(options);
 
    // Run teardown
    this.teardown({ shallow: true });
 
    // Fire an event hook before the
    // custom destroy logic is run
    this.fireStatic('before destroy');
 
    // If custom destroy logic has been
    // defined on the prototype then run it.
    Eif (this._destroy) this._destroy();
 
    // Trigger a `destroy` event
    // for custom Modules to bind to.
    this.fireStatic('destroy');
 
    // Unbind any old event listeners
    this.off();
 
    // Set a flag to say this view
    // has been destroyed. This is
    // useful to check for after a
    // slow ajax call that might come
    // back after a view has been detroyed.
    this.destroyed = true;
 
    // Clear references
    this.el = this.model = this.parent = this._modules = this._ids = this._id = null;
  };
 
  /**
   * Destroys all children.
   *
   * Is this needed?
   *
   * @return {Module}
   * @api public
   */
  proto.empty = function() {
    var l = this.children.length;
    while (l--) this.children[l].destroy();
    return this;
  };
 
  /**
   * Fetches all descendant elements
   * from the given root element.
   *
   * @param  {Element} root
   * @return {undefined}
   * @api private
   */
  proto._fetchEls = function(root) {
    Iif (!root) return;
    this.each(function(child) {
      child.mount(util.byId(child._fmid, root));
      child._fetchEls(child.el || root);
    });
  };
 
  /**
   * Associate the view with an element.
   * Provide events and lifecycle methods
   * to fire when the element is newly
   * associated.
   *
   * @param {Element} el
   * @return {Element}
   */
  proto.mount = function(el) {
    if(this.el !== el) {
      this.fireStatic('before mount');
      this.el = el;
      if(this._mount) this._mount();
      this.fireStatic('mount');
    }
 
    return this.el;
  };
 
  /**
   * Recursively fire unmount events on
   * children. To be called when a view's
   * children are implicitly removed from
   * the DOM (e.g. setting innerHTML)
   *
   * @api private
   */
  proto._unmountChildren = function() {
    this.each(function(child) {
      child._unmount();
    });
  };
 
  
  /*_setEl   * Recursively fire unmount events on
   * a view and its children. To be
   * called when a view'is implicitly
   * removed from the DOM (e.g. _setEl)
   *
   * @api private
   */
  proto._unmount = function() {
    this._unmountChildren();
    this.fireStatic('unmount');
  }
 
  /**
   * Returns the Module's root element.
   *
   * If a cache is present it is used,
   * else we search the DOM, else we
   * find the closest element and
   * perform a querySelector using
   * the view._fmid.
   *
   * @return {Element|undefined}
   * @api private
   */
  proto._getEl = function() {
    Iif (!util.hasDom()) return;
    return this.mount(this.el || document.getElementById(this._fmid) || undefined);
  };
 
  /**
   * Sets a root element on a view.
   * If the view already has a root
   * element, it is replaced.
   *
   * IMPORTANT: All descendent root
   * element caches are purged so that
   * the new correct elements are retrieved
   * next time Module#getElement is called.
   *
   * @param {Element} el
   * @return {Module}
   * @api private
   */
  proto._setEl = function(el) {
    var existing = this.el;
    var parentNode = existing && existing.parentNode;
 
    // If the existing element has a context, replace it
    if (parentNode) {
      parentNode.replaceChild(el, existing);
      this._unmount();
    }
 
    // Update cache
    this.mount(el);
 
    return this;
  };
 
  /**
   * Empties the destination element
   * and appends the view into it.
   *
   * @param  {Element} dest
   * @return {Module}
   * @api public
   */
  proto.inject = function(dest) {
    if (dest) {
      dest.innerHTML = '';
      this.insertBefore(dest, null);
      this.fireStatic('inject');
    }
 
    return this;
  };
 
  /**
   * Appends the view element into
   * the destination element.
   *
   * @param  {Element} dest
   * @return {Module}
   * @api public
   */
  proto.appendTo = function(dest) {
    return this.insertBefore(dest, null);
  };
 
  /**
   * Inserts the view element before the
   * given child of the destination element.
   *
   * @param  {Element} dest
   * @param  {Element} beforeEl
   * @return {Module}
   * @api public
   */
  proto.insertBefore = function(dest, beforeEl) {
    Eif (this.el && dest && dest.insertBefore) {
      dest.insertBefore(this.el, beforeEl);
 
      // This badly-named event is for legacy reasons; perhaps 'insert' would be better here?
      this.fireStatic('appendto');
    }
 
    return this;
  };
 
  /**
   * Returns a JSON represention of
   * a FruitMachine Module. This can
   * be generated serverside and
   * passed into new FruitMachine(json)
   * to inflate serverside rendered
   * views.
   *
   * @return {Object}
   * @api public
   */
  proto.toJSON = function() {
    var json = {};
    json.children = [];
 
    // Recurse
    this.each(function(child) {
      json.children.push(child.toJSON());
    });
 
    json.id = this.id();
    json.fmid = this._fmid;
    json.module = this.module();
    json.model = this.model.toJSON();
    json.slot = this.slot;
 
    // Fire a hook to allow third
    // parties to alter the json output
    this.fireStatic('tojson', json);
 
    return json;
  };
 
  // Events
  proto.on = events.on;
  proto.off = events.off;
  proto.fire = events.fire;
  proto.fireStatic = events.fireStatic;
 
  // Allow Modules to be extended
  Module.extend = extend(util.keys(proto));
 
  // Adding proto.Model after
  // Module.extend means this
  // key can be overwritten.
  proto.Model = fm.Model;
 
  return Module;
};