以上我們分析的編寫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裏的內容。