分析boostrap tags-input组件并进行二次封装开发-3

以上我们分析的编写jquery组件的一般思路

接下来我们需要针对编写的细节部分进行分析了

我们按照组件的使用时调用顺序进行分析

组件使用的方式在html中插入如下代码

<input type="text" value="Amsterdam,Washington,Sydney,Beijing,Cairo" data-role="tagsinput" />

而组件的启动代码如下

$(function() {
    $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
  });

组件使用匿名函数并将$及jQuery传入匿名函数内提供使用,功能是会选出所有data-role为tagsinput的input并执行注册到jquery对象原型链的tagsinput的函数。

接下来分析一下组件的构造函数

  function TagsInput(element, options) {
    //element组件主节点
    this.itemsArray = [];

    this.$element = $(element);
    this.$element.hide();

    this.isSelect = (element.tagName === 'SELECT');
    this.multiple = (this.isSelect && element.hasAttribute('multiple'));
    this.objectItems = options && options.itemValue;
    this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';
    this.inputSize = Math.max(1, this.placeholderText.length);

    this.$container = $('<div class="bootstrap-tagsinput"></div>');
    this.$input = $('<input type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);

    this.$element.before(this.$container);

    this.build(options);
  }

——————————————————————————————————————————————————

对于构造函数的理解,首先根据组件的DOM元素(由使用者进行编写),此input对应组件用于组件的参数设置,对应构造函数里的$element


——————————————————————————————————————————————————

$container为组件的容器DOM对应为

<div class="boostrap-tagsinput">...</div>

——————————————————————————————————————————————————

$input为container后面的空白input用于占位对应为

<input type="text" placeholder>

———————————————————————————————————————————————————

总结一下组件的DOM元素组成如下

———————————————————————————————————————————————————
最后的this.build(options)是根据$element的参数的设置渲染构建组件。

至此其实我们可以在深入分析一下,elements与options这两部分应该就是controller控制整个组件的内容构建向模型发送数据,

$input,$container是view用于展示数据,

而build应该就是model用于控制数据结构。

这也是一个小型的MVC框架,其实MVC的思想处处存在,这应该是一个普适性的道理。

今天就到这里,下一次就相信分析一下model里的内容。

猜你喜欢

转载自blog.csdn.net/u013693703/article/details/80748575
今日推荐