Jquery学习笔记——代码组织

核心原则:

 按功能组织你的代码:模块,服务等
 无代码重复,使用inheritance解决
 松耦合,代码之间通过 custom event,pub/sub完成消息传递

封装:

使用对象进行封装的好处是:解决消除匿名函数,以配置参数为中心,更方便去重构和重用。比如对事件处理函数,定义为_开头的函数,隐含其为工具函数或私有函数,一个简单的实例:

var myFeature = {
	myProperty : 'hello',
	
	myMethod : function() {
	    console.log(myFeature.myProperty);
	},
	
	init : function(settings) {
	    myFeature.settings = settings;
	},
	
	readSettings : function() {
	    console.log(myFeature.settings);
	}
};

myFeature.myProperty; // 'hello'
myFeature.myMethod(); // logs 'hello'
myFeature.init({ foo : 'bar' });
myFeature.readSettings(); // logs { foo : 'bar' }


如何将对象应用在Jquery编写的程序中,一个典型的Jquery程序如下:

$(document).ready(function() {
	$('#myFeature li')
	.append('<div/>')
	.click(function() {
	  var $this = $(this);
	  var $div = $this.find('div');
	  $div.load('foo.php?item=' +
	    $this.attr('id'),
	    function() {
	      $div.show();
	      $this.siblings()
	        .find('div').hide();
	    }
	  );
	});
});


可以从以下几个方面进行优化:1. 将和功能无关的部分分离,如常量字符串,多个函数都会用到的变量; 2. 打破chain 方便修改功能

var myFeature = {
		init : function(settings) {
			myFeature.config = {
					$items : $('#myFeature li'),
					$container : $('<div class="container"></div>'),
					urlBase : '/foo.php?item='
			};

			// allow overriding the default config
			$.extend(myFeature.config, settings || {});

			myFeature.setup();
		},

		setup : function() {  //开始功能处理
			myFeature.config.$items
			.each(myFeature.createContainer)
			.click(myFeature.showItem);
		},

		createContainer : function() {
			var $i = $(this),
			$c = myFeature.config.$container.clone()
			.appendTo($i);

			$i.data('container', $c);
		},

		buildUrl : function() {
			return myFeature.config.urlBase +
			myFeature.$currentItem.attr('id');
		},

		showItem : function() {
			var myFeature.$currentItem = $(this);
			myFeature.getContent(myFeature.showContent);
		},

		getContent : function(callback) {
			var url = myFeature.buildUrl();
			myFeature.$currentItem
			.data('container').load(url, callback);
		},

		showContent : function() {
			myFeature.$currentItem
			.data('container').show();
			myFeature.hideContent();
		},

		hideContent : function() {
			myFeature.$currentItem.siblings()
			.each(function() {
				$(this).data('container').hide();
			});
		}
};

$(document).ready(myFeature.init);


修改好的状态:

      1. 去除了匿名函数
      2. 将配置信息从函数中移除,并放在中心位置
      3. 解除了chain,保证重用性

使用函数:modelPattern

使用对象可以很好地将数据和函数分开,但没法对函数的访问方式进行限定,如无法对函数和属性进行private限定,一个简单实例

var feature =(function() {

//	private variables and functions
	var privateThing = 'secret',
	publicThing = 'not secret',

	changePrivateThing = function() {
		privateThing = 'super secret';
	},

	sayPrivateThing = function() {
		console.log(privateThing);
		changePrivateThing();
	};

//	public API
	return {
		publicThing : publicThing,
		sayPrivateThing : sayPrivateThing
	}

})();

feature.publicThing; // 'not secret'

feature.sayPrivateThing();
//logs 'secret' and changes the value of privateThing


下面使用这种方式,继续对jquery程序进行优化

$(document).ready(function() {
	var feature = (function() {

		var $items = $('#myFeature li'), $container = $('<div class="container"></div>'), $currentItem,

		urlBase = '/foo.php?item=',

		createContainer = function() {
			var $i = $(this), $c = $container.clone().appendTo(
					$i);

			$i.data('container', $c);
		},

		buildUrl = function() {
			return urlBase + $currentItem.attr('id');
		},

		showItem = function() {
			var $currentItem = $(this);
			getContent(showContent);
		},

		showItemByIndex = function(idx) {
			$.proxy(showItem, $items.get(idx));
		},

		getContent = function(callback) {
			$currentItem.data('container').load(buildUrl(),
					callback);
		},

		showContent = function() {
			$currentItem.data('container').show();
			hideContent();
		},

		hideContent = function() {
			$currentItem.siblings().each(function() {
				$(this).data('container').hide();
			});
		};

		$items.each(createContainer).click(showItem);

		return {
			showItemByIndex : showItemByIndex
		};
	})();

	feature.showItemByIndex(0);
});


管理依赖

可 使用RequiredJS 来管理JS之间的依赖

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于 jQuery 的事件,我可以和你分享一些学习笔记。 1. 绑定事件 在 jQuery 中,我们可以通过以下方式来绑定事件: ``` $(selector).event(function(){ // 事件处理程序 }) ``` 其中,`selector` 表示要绑定事件的元素,`event` 表示要绑定的事件类型,比如 `click`、`mouseover` 等等。事件处理程序则是在事件触发时要执行的代码块。 2. 多个事件绑定 我们可以通过 `on()` 方法来同时绑定多个事件: ``` $(selector).on({ event1: function(){ // 事件处理程序1 }, event2: function(){ // 事件处理程序2 } }) ``` 这样,当 `event1` 或 `event2` 中任意一个事件触发时,对应的处理程序都会被执行。 3. 解除事件 如果需要解除某个元素的事件处理程序,可以使用 `off()` 方法: ``` $(selector).off(event); ``` 其中,`event` 表示要解除的事件类型。如果不指定事件类型,则会解除该元素上所有的事件处理程序。 4. 事件委托 在 jQuery 中,我们可以使用事件委托来提高性能。事件委托是指将事件绑定到父元素上,而不是绑定到子元素上,然后通过事件冒泡来判断是哪个子元素触发了该事件。这样,当子元素数量较多时,只需要绑定一次事件,就可以监听到所有子元素的事件。 ``` $(selector).on(event, childSelector, function(){ // 事件处理程序 }) ``` 其中,`selector` 表示父元素,`event` 表示要绑定的事件类型,`childSelector` 表示要委托的子元素的选择器,事件处理程序则是在子元素触发事件时要执行的代码块。 以上是 jQuery 中事件的一些基本操作,希望对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值