如何在javascript中编写可自定义的函数?

时间:2017-04-12 06:09:04

标签: javascript web-component

我第一次为我的项目编写可重用的组件。这是一个简单的Dropdownlist组件,它有几个属性。我按照Revealing Prototype Pattern来实现这个。

这是我的component.js和使用来自component.js的DropdownList的html页面



   var Components = function(){

};

Components.prototype = function(){

	var guid = function () {
	    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
		      			s4() + '-' + s4() + s4() + s4();
        };

        var s4 = function () {

          return Math.floor((1 + Math.random()) * 0x10000)
		          .toString(16)
		          .substring(1);
	};

        var getDropDownList = function(){
          return new DropDownList();
	};

	var DropDownList = function(){
	  this._id = guid();
	};

	DropDownList.prototype = function(){

			var data = [];
			var placeholderid = undefined;
			var selectedText = "";
			var selectedIndex = NaN;
			var defaultText = "";

			var setData = function(objArray){
				data = objArray;
				selectedIndex = 0;
			};
			var getData = function(){
				return data;
			};

			var addData = function(obj){
				data.push(obj);
			};

			var clearData = function(){
				data = [];
			};

			var setPlaceHolder = function(id){
				placeholderid = id;
			};

			var getPlaceHolder = function(){
				return placeholderid;
			};

			var setSelectedText = function(text){
				selectedText = text;
			};

			var getSelectedText = function(){
				return selectedText;
			};

			var setSelectedIndex = function(index){
				selectedIndex = index;
			};

			var getSelectedIndex = function(){
				return selectedIndex;
			};

			var setDefaultText = function(text){
				defaultText = text;
			};

			var getDefaultText = function(){
				return (defaultText == "" ? "Choose" : defaultText);
			};

			var onItemChange = function(onItemChangeCallback){
					
					//Append required html components to place holder
					$(`#${placeholderid}`).append(`<div class='dropdown' id=${this._id}><button class='btn btn-default dropdown-toggle' type='button' data-toggle='dropdown' name='dropdownButton'><span name='Selected-Text'>${getDefaultText()}&emsp;</span><span class='caret'></span></button><ul class='dropdown-menu'></ul></div>`);

					var mainComponent = document.getElementById(this._id);
					var itemContainer = $(mainComponent).find('ul');
					$(itemContainer).empty();

					if(data.length > 0){

						for(let i = 0; i < data.length; i++){

							$(itemContainer).append(`<li><a>${data[i]}</a></li>`);// Add item to the list
							var currentAnchor = $(itemContainer).find('li')[i];

							/*Default on item click behavior*/
							$(currentAnchor).on('click',function(e){ // on list item click
								e.preventDefault();
								setSelectedText(data[i]); // set current selected data to selectedText property
								setSelectedIndex(i); // set current selected index to selectedText property
								$(mainComponent).children('button').eq(0).children('span').eq(0).prop('innerHTML',getSelectedText() + '&emsp;');//Set selected text to dropdownlist text


								/*Process user defined behavior*/
								onItemChangeCallback();
							});
							
						}
					}
					
				};

				/* Public properties and events of dropdownlist */
				return{
					getData: getData,
					setData:setData,
					addData : addData,
					clearData : clearData,
					getSelectedText : getSelectedText,
					getSelectedIndex : getSelectedIndex,
					setPlaceHolder : setPlaceHolder,
					getPlaceHolder : getPlaceHolder,
					onItemChange: onItemChange
				}
			}();

		return{
			getDropDownList : getDropDownList
		};
	}();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">



<div id="place_holder_1">
      <!--Place holder to place dropdownlist-->
</div>
		


<script type="text/javascript">

	$(document).ready(function(){
	    var components = new Components();

	    var dummyArray = ["None","Item 1","Item 2","Item 3","Item 4","Item 5"];///Prepare Dummy Data

	    var ddlTest = components.getDropDownList(); //get a new dropdownlist instance
		ddlTest.setData(dummyArray);//Set the data of the dropdownlist
		ddlTest.setPlaceHolder("place_holder_1");//Set a place holder for the dropdownlist

		ddlTest.onItemChange(function(){ 

		    if(ddlTest.getSelectedText() === "Item 1"){
			  alert("This is executed from user defined callback!");

		    }
					
		    console.log(ddlTest.getSelectedText());
                    console.log(ddlTest.getSelectedIndex());
					
	       });
           });
 </script>
&#13;
&#13;
&#13;

DropDownList.prototype onItemChange() 函数中,它接受一个函数作为参数允许开发人员在组件的默认行为完成后实现自己的代码。

问题是,这是提供组件的可自定义事件的正确方法。我的代码欢迎任何建议。感谢。

0 个答案:

没有答案