<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>jQuery &#8211; Mach3.laBlog</title>
	<atom:link href="https://blog.mach3.jp/tag/jquery/feed" rel="self" type="application/rss+xml" />
	<link>https://blog.mach3.jp</link>
	<description></description>
	<lastBuildDate>Sun, 25 Dec 2016 00:59:59 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>
	<item>
		<title>細かすぎて伝わらないjQuery拡張 (終) &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/25/ac2016-25.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Sun, 25 Dec 2016 00:59:59 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4332</guid>

					<description><![CDATA[今年のアドベントカレンダーは、23ほどのjQuery拡張関数を連日ご紹介してまいりました。 おさらい 毎度お世話になっているjQueryで、毎回書いてしまうちょこざいな関数をつらつらとしたためて来ました。 実際の中身はj [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p>今年のアドベントカレンダーは、23ほどのjQuery拡張関数を連日ご紹介してまいりました。</p>



<span id="more-4332"></span>



<h2 class="wp-block-heading">おさらい</h2>



<p>毎度お世話になっているjQueryで、毎回書いてしまうちょこざいな関数をつらつらとしたためて来ました。 実際の中身はjQueryの機能への依存度はさほど高くない（？）ので、少しいじれば別にjQueryと一緒に使わなくても良い物もあったりします。 強いて言えば元々そんなにjQueryは好きではありませんが、結局使うことが多いので仕方ないですね。</p>



<h2 class="wp-block-heading">インデックス</h2>



<p>23個まとめてリストにしておきます。目次のようなもの。</p>



<dl>
<dt><strong><a href="/2016/12/02/ac2016-02.html">$.chainCase(str) :String</a></strong></dt>
<dd>キャメルケースの文字列をチェインケース・スネークケースに変換する<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/03/ac2016-03.html">$.classify(obj) :Function</a></strong></dt>
<dd>クラスライクな関数を生成する<br />
jQuery依存度 : 中</dd>
<dt><strong><a href="/2016/12/04/ac2016-04.html">$.configify(obj) :Object</a></strong></dt>
<dd>オブジェクトに options を設定・変更する config() メソッドを実装する<br />
jQuery依存度 : 中</dd>
<dt><strong><a href="/2016/12/05/ac2016-05.html">$.dig(path, obj) :Any</a></strong></dt>
<dd>ドットシンタックスの文字列を渡すとそのオブジェクトを掘り起こして返す<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/06/ac2016-06.html">$.escapeHTML(str) :String</a></strong></dt>
<dd>HTML文字列をエスケープする<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/07/ac2016-07.html">$.eventify(obj) :Object</a></strong></dt>
<dd>オブジェクトにイベント管理のメソッド（on, off, trigger）を実装する<br />
jQuery依存度 : 低-中</dd>
<dt><strong><a href="/2016/12/08/ac2016-08.html">$.attributify(obj) :Object</a></strong></dt>
<dd>オブジェクトに属性管理のメソッド .attr() を実装する<br />
jQuery依存度 : 低</dd>
<dt><strong><a href="/2016/12/09/ac2016-09.html">$.format(template, str, str&#8230;) :String</a></strong></dt>
<dd>&#8220;%s%d&#8221; 形式のフォーマットに則って整形された文字列を返す<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/10/ac2016-10.html">$.formatNumber(num) :String</a></strong></dt>
<dd>数値を三桁ずつカンマで区切った文字列で返す<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/11/ac2016-11.html">$.observe(callback) :Deferred</a></strong></dt>
<dd>コールバック関数を渡してその返り値を監視する<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/12/ac2016-12.html">$.parseQuery(str, asArray) :String</a></strong></dt>
<dd>URLのサーチ文字列（&#8221;?key=value&amp;key2=value2&#8243; ）をパースする<br />
jQuery依存度 : 低</dd>
<dt><strong><a href="/2016/12/13/ac2016-13.html">$.parseURL(str) :Object</a></strong></dt>
<dd>URL文字列をホスト名やサーチ文字列・ハッシュなどにパースする<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/14/ac2016-14.html">$.random(start, end) :Any</a></strong></dt>
<dd>範囲の間からランダムな数値を取得したり、リストの中からランダムに値を取得する<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/15/ac2016-15.html">$.rebase(obj, pattern) :Object</a></strong></dt>
<dd>オブジェクトに属しているメソッドをそのオブジェクトに bind する<br />
jQuery依存度 : 低</dd>
<dt><strong><a href="/2016/12/16/ac2016-16.html">$.render(template, data) :String|Function</a></strong></dt>
<dd>単機能のテンプレート関数<br />
jQuery依存度 : 低</dd>
<dt><strong><a href="/2016/12/17/ac2016-17.html">$.scrollTo(dest, offset, options, selector) :void</a></strong></dt>
<dd>ページあるいは要素の中身をアニメーションでスクロールする<br />
jQuery依存度 : 高</dd>
<dt><strong><a href="/2016/12/18/ac2016-18.html">$.fn.serializeObject() :Object</a></strong></dt>
<dd>フォーム要素をシリアライズして、オブジェクトで返す<br />
jQuery依存度 : 高</dd>
<dt><strong><a href="/2016/12/19/ac2016-19.html">$.fn.extract(asArray) :Object|Array</a></strong></dt>
<dd>非Form要素の内容をシリアライズする<br />
jQuery依存度 : 高</dd>
<dt><strong><a href="/2016/12/20/ac2016-20.html">$.series(callback, callback &#8230;) :Deferred</a></strong></dt>
<dd>連鎖的に直列処理を実行する<br />
jQuery依存度 : 高</dd>
<dt><strong><a href="/2016/12/21/ac2016-21.html">$.fn.submitAsync(props) :Deferred</a></strong></dt>
<dd>Form要素を非同期でsubmitする<br />
jQuery依存度 : 高</dd>
<dt><strong><a href="/2016/12/22/ac2016-22.html">$.times(count, callback) :void</a></strong></dt>
<dd>n回処理を繰り返す<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/23/ac2016-23.html">$.timing.*</a></strong></dt>
<dd>User Timing API のラッパー<br />
jQuery依存度 : 無</dd>
<dt><strong><a href="/2016/12/24/ac2016-24.html">$.fn.transition(props, options) :jQueryObject</a></strong></dt>
<dd>$.fn.animate() のようにCSS Transitionを実現する<br />
jQuery依存度 : 高</dd>
</dl>



<h2 class="wp-block-heading">リポジトリ</h2>



<p>全て纏めた物をGithubのリポジトリにしてあります。ご自由にどうぞ。</p>



<p><a href="https://github.com/mach3/jquery-tiny-extentions">jquery-tiny-extentions @ GitHub</a></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>それでは皆様、良い年末をお過ごしください。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (24) &#034;$.fn.transition&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/24/ac2016-24.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Sat, 24 Dec 2016 00:30:23 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4318</guid>

					<description><![CDATA[$.fn.transition は、$.fn.animate の様にCSS Transitionを実現する関数です。 $.fn.transition(props, options) CSS Transition によるア [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.fn.transition</strong> は、<a href="http://api.jquery.com/animate/">$.fn.animate</a> の様にCSS Transitionを実現する関数です。</p>



<span id="more-4318"></span>



<h2 class="wp-block-heading">$.fn.transition(props, options)</h2>



<p>CSS Transition によるアニメーションはJavaScriptによるアニメーションに比べてパフォーマンスが非常によく、綺麗です。 しかし一方で、非対応環境の為に .animate() を使わなければならない事が多いので、 両者で動作するように対応できる関数をしたためてみました。</p>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// 要素を left: 100 に移動</span>
$(<span class="hljs-string">".item"</span>).transition({
    <span class="hljs-attr">left</span>: <span class="hljs-number">100</span>
}, {
    <span class="hljs-attr">duration</span>: <span class="hljs-number">300</span>, <span class="hljs-comment">// 所要時間 300ms</span>
    <span class="hljs-attr">delay</span>: <span class="hljs-number">100</span>, <span class="hljs-comment">// アニメーション開始までのディレイ 100ms</span>
    <span class="hljs-attr">easing</span>: <span class="hljs-string">"linear"</span> <span class="hljs-comment">// イージング関数の指定</span>
});
</code></span></pre>


<p>基本的な使い方は <strong>.animate()</strong> と概ね同じです。</p>



<ul class="wp-block-list">
<li>第一引数 : アニメーションするスタイル</li>



<li>第二引数 : オプション</li>
</ul>



<p>CSS Transition に対応していないレガシーな環境では $.fn.animate で代替しています。 イージング関数名として渡せるのは jQuery.easing の名前ではなく、 CSS Transition で定義されている名前です。（ease | linear | ease-in | ease-out | ease-in-out）</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// 要素をアニメーション後、削除</span>
$(<span class="hljs-string">".item"</span>).transition({
    <span class="hljs-attr">opacity</span>: <span class="hljs-number">0</span>,
    <span class="hljs-attr">right</span>: <span class="hljs-number">500</span>
}, {
    <span class="hljs-attr">done</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        $(<span class="hljs-keyword">this</span>).remove();
    }
});
</code></span></pre>


<p><strong>.animate()</strong> 同様に、オプションで done を渡して完了時の処理を実装できます。 <strong>.animate()</strong> にあるその他多数のオプションは使えません。</p>



<p>また、stop() とかはできません。とまりません。</p>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.extend($.support, {
    <span class="hljs-attr">cssTransition</span>: (<span class="hljs-string">"transition"</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"i"</span>).style)
});

$.transition = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">props, options</span>)</span>{
    <span class="hljs-keyword">var</span> o, transition = &#91;];

    o = $.extend({
        <span class="hljs-attr">duration</span>: <span class="hljs-number">400</span>,
        <span class="hljs-attr">delay</span>: <span class="hljs-number">0</span>,
        <span class="hljs-attr">easing</span>: <span class="hljs-string">"ease"</span>,
        <span class="hljs-attr">done</span>: $.noop
    }, options);

    <span class="hljs-keyword">if</span>(! $.support.cssTransition){
        <span class="hljs-keyword">switch</span>(o.easing){
            <span class="hljs-keyword">case</span> <span class="hljs-string">"ease"</span>: o.easing = <span class="hljs-string">"swing"</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"ease-in"</span>: o.easing = <span class="hljs-string">"easeInSine"</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"ease-out"</span>: o.easing = <span class="hljs-string">"easeOutSine"</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"ease-in-out"</span>: o.easing = <span class="hljs-string">"easeInOutSine"</span>;
            <span class="hljs-keyword">default</span>: <span class="hljs-keyword">break</span>;
        }
        o.easing = (o.easing <span class="hljs-keyword">in</span> $.easing) ? o.easing : <span class="hljs-string">"swing"</span>;

        <span class="hljs-keyword">this</span>.stop().delay(o.delay).animate(props, {
            <span class="hljs-attr">duration</span>: o.duration,
            <span class="hljs-attr">easing</span>: o.easing,
            <span class="hljs-attr">done</span>: o.done
        });

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }

    $.each(props, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">key, value</span>)</span>{
        transition.push(
            &#91;
                key,
                o.duration + <span class="hljs-string">"ms"</span>,
                o.easing,
                o.delay + <span class="hljs-string">"ms"</span>
            ].join(<span class="hljs-string">" "</span>)
        );
    });
    transition = transition.join(<span class="hljs-string">","</span>);

    <span class="hljs-keyword">this</span>.each(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">var</span> el = $(<span class="hljs-keyword">this</span>),
            done = (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>)</span>{
                o.done.call(<span class="hljs-keyword">this</span>, e);
                $(<span class="hljs-keyword">this</span>).css(<span class="hljs-string">"transition"</span>, <span class="hljs-string">""</span>).off(<span class="hljs-string">"transitionend"</span>, done);
            }).bind(<span class="hljs-keyword">this</span>);

        el.css(<span class="hljs-string">"transition"</span>, transition)
        .on(<span class="hljs-string">"transitionend"</span>, done)
        .css(props);

        setTimeout(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            el.trigger(<span class="hljs-string">"transitionend"</span>);
        }, o.duration + <span class="hljs-number">33</span>);
    });

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
};
</code></span></pre>


<p>ベンダープレフィックス無しの &#8220;transition&#8221; を持たない環境は、使えない物とみなしています。 （面倒だったのもありますが、必要性もあまり感じなかった為）</p>



<p>非対応環境ではイージング関数を jQuery.easing の名前に書き換えています。 といっても、デフォルトで実装されているのは &#8220;swing&#8221; と &#8220;linear&#8221; だけなので、 <a href="http://gsgd.co.uk/sandbox/jquery/easing/">jQuery.easing プラグイン</a> も含めて、近しい物を割り当てています。 こちらも一緒に使う事で表現は豊かになりますが、なければないで、そこらへんが全部 &#8220;swing&#8221; になるだけです。</p>



<p>完了時の処理に &#8220;transitionend&#8221; を利用していますが、 これは実際に値が変わってトランジションが発生していないと発火しない代物なので、 時間経過と共に無理やり発火させています。 「アニメーションしないアニメーション」の完了時に何かしたい事なんてないだろうと思いますが、念のため。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (23) &#034;$.timing&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/23/ac2016-23.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Fri, 23 Dec 2016 00:26:08 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4314</guid>

					<description><![CDATA[$.timing は、User Timing API のラッパーです。 わずかな機能だけですが、非対応環境に擬似的に対応してみました。 User Timing API とは User Timing APIは、Webページ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.timing</strong> は、<a href="https://www.w3.org/TR/user-timing/">User Timing API</a> のラッパーです。 わずかな機能だけですが、非対応環境に擬似的に対応してみました。</p>



<span id="more-4314"></span>



<h2 class="wp-block-heading">User Timing API とは</h2>



<p>User Timing APIは、Webページ上のパフォーマンスを計測するためのインターフェースです。 その役割と使い方は下記URLのエントリーで解説されています。</p>



<ul class="wp-block-list">
<li><a href="https://www.html5rocks.com/ja/tutorials/webperformance/usertiming/">User Timing API: あなたの Web アプリをもっと理解するために &#8211; HTML5 Rocks</a></li>
</ul>



<p>ものすごくざっくりと使い方を紹介すると、こんな感じ。</p>



<ul class="wp-block-list">
<li>mark() を使って任意のタイミングでタイムスタンプを「マーク」として記録</li>



<li>measure() を使って、記録したマーク間の所要時間を計測</li>



<li>タイムスタンプは1/1000ミリ秒という高精度で記録される</li>
</ul>



<p>執筆時点でのメジャーどころの対応状況は IE10+ / Edge / Firefox / Chrome / Opera 40+ となっていて、 IE9以前やSafari（iOS含）は非対応です。</p>



<h2 class="wp-block-heading">$.timing</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// マークを記録</span>
$.timing.mark(<span class="hljs-string">"foo"</span>);
$.timing.mark(<span class="hljs-string">"bar"</span>);

<span class="hljs-comment">// マーク間の所要時間を記録</span>
$.timing.measure(<span class="hljs-string">"from_foo_to_bar"</span>, <span class="hljs-string">"foo"</span>, <span class="hljs-string">"bar"</span>);

<span class="hljs-comment">// 名前からタイムスタンプを取得</span>
$.timing.get(<span class="hljs-string">"from_foo_to_bar"</span>); <span class="hljs-comment">// =&gt; number</span>

<span class="hljs-comment">// 記録したマークを全て取得</span>
$.timing.marks(); <span class="hljs-comment">// =&gt; object</span>

<span class="hljs-comment">// 記録したメジャーを全て取得</span>
$.timing.measures(); <span class="hljs-comment">// =&gt; object</span>
</code></span></pre>


<ul class="wp-block-list">
<li>.mark(name) でそのタイミングのタイムスタンプを記録します</li>



<li>.measure(name, start, end) で、開始マークから終了マークまでの所要時間を記録します</li>



<li>.get(name) で名前からマーク・メジャーの時間を数値で取得します</li>



<li>.marks() / .measures() で記録したマーク・メジャーを全てオブジェクトで取得</li>
</ul>



<h2 class="wp-block-heading">Polyfill とは呼べないモノ</h2>



<p>$.timing はほんの一部の機能しか実装していません。 また、擬似的に再現してみたとはいえ1/1000ミリ秒単位で計測はちょっと出来無さそうで、 Polyfillと呼ぶにはあまりに片手落ちですね。</p>



<p><a href="https://github.com/zloirock/core-js">core-js</a> あたりでPolyfillを書いているかも？と思いましたが、 中の人が<a href="https://github.com/zloirock/core-js/issues/130">「無理デス」</a> とおっしゃっています。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Thanks for proposal, but it can&#8217;t be polyfilled &#8211; only little part and with serious limitations.<br />
  <a href="https://github.com/zloirock/core-js/issues/130">https://github.com/zloirock/core-js/issues/130</a></p>
</blockquote>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.timing = {
    <span class="hljs-attr">_supported</span>: (<span class="hljs-string">"performance"</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">window</span>) &amp;&amp; (<span class="hljs-string">"timing"</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">window</span>.performance),
    <span class="hljs-attr">_data</span>: {},
    <span class="hljs-attr">_start</span>: (<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()).getTime(),

    <span class="hljs-attr">mark</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>)</span>{
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">this</span>._supported){
            <span class="hljs-built_in">window</span>.performance.mark(name);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">this</span>._data&#91;name] = {
                <span class="hljs-attr">type</span>: <span class="hljs-string">"mark"</span>,
                <span class="hljs-attr">startTime</span>: (<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()).getTime() - <span class="hljs-keyword">this</span>._start
            };
        }
    },

    <span class="hljs-attr">marks</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getEntries(<span class="hljs-string">"mark"</span>, <span class="hljs-string">"startTime"</span>);
    },

    <span class="hljs-attr">measure</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name, start, end</span>)</span>{
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">this</span>._supported){
            <span class="hljs-built_in">window</span>.performance.measure(name, start, end);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">this</span>._data&#91;name] = {
                <span class="hljs-attr">type</span>: <span class="hljs-string">"measure"</span>,
                <span class="hljs-attr">duration</span>: <span class="hljs-keyword">this</span>.get(end) - <span class="hljs-keyword">this</span>.get(start)
            };
        }
    },

    <span class="hljs-attr">measures</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getEntries(<span class="hljs-string">"measure"</span>, <span class="hljs-string">"duration"</span>);
    },

    <span class="hljs-attr">get</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>)</span>{
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">this</span>._supported){
            <span class="hljs-keyword">var</span> items = <span class="hljs-built_in">window</span>.performance.getEntriesByName(name);
            <span class="hljs-keyword">return</span> items.length ? items&#91;<span class="hljs-number">0</span>].startTime : <span class="hljs-keyword">void</span> <span class="hljs-number">0</span>;
        }
        <span class="hljs-keyword">return</span> (name <span class="hljs-keyword">in</span> <span class="hljs-keyword">this</span>._data) ? <span class="hljs-keyword">this</span>._data&#91;name].startTime : <span class="hljs-keyword">void</span> <span class="hljs-number">0</span>;
    },

    <span class="hljs-attr">getEntries</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">type, key</span>)</span>{
        <span class="hljs-keyword">var</span> data = {};
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">this</span>._supported){
            <span class="hljs-built_in">window</span>.performance.getEntriesByType(type)
            .forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
                data&#91;item.name] = item&#91;key];
            });
        } <span class="hljs-keyword">else</span> {
            $.each(<span class="hljs-keyword">this</span>._data, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name, item</span>)</span>{
                <span class="hljs-keyword">if</span>(item.type === type){
                    data&#91;name] = item&#91;key];
                }
            });
        }
        <span class="hljs-keyword">return</span> data;
    }
};
</code></span></pre>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (22) &#034;$.times&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/22/ac2016-22.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Thu, 22 Dec 2016 00:24:58 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4310</guid>

					<description><![CDATA[$.times() は、n回処理を繰り返してくれる関数です。 $.times(count, callback) 使い方 第一引数に繰り返したい回数を整数で、 第二引数に実行したい関数を渡します。 関数には0からはじまるイ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.times()</strong> は、n回処理を繰り返してくれる関数です。</p>



<span id="more-4310"></span>



<h2 class="wp-block-heading">$.times(count, callback)</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">var</span> str = <span class="hljs-string">""</span>;

$.times(<span class="hljs-number">10</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">index</span>)</span>{
    str += index;
});

<span class="hljs-built_in">console</span>.log(str); <span class="hljs-comment">// =&gt; "0123456789"</span>
</code></span></pre>


<p>第一引数に繰り返したい回数を整数で、 第二引数に実行したい関数を渡します。 関数には0からはじまるインデックスが渡されます。</p>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.times = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">count, callback</span>)</span>{
    <span class="hljs-keyword">var</span> i = count;
    <span class="hljs-keyword">while</span>(i--){
        callback(count - i - <span class="hljs-number">1</span>);
    }
};
</code></span></pre>


<p>正直細かすぎたかなって思ってます。</p>



<p>実際にプロダクトのコードに使われる事はあまりなく、デモデータの生成やテスト等で使ったりはします。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (21) &#034;$.fn.submitAsync&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/21/ac2016-21.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Wed, 21 Dec 2016 00:18:24 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4302</guid>

					<description><![CDATA[$.fn.submitAsync() は、form要素を非同期でsubmitするための関数です。 $.fn.submitAsync(options) 使い方 返り値は $.ajax() なので、then/done 等で結 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.fn.submitAsync()</strong> は、form要素を非同期でsubmitするための関数です。</p>



<span id="more-4302"></span>



<h2 class="wp-block-heading">$.fn.submitAsync(options)</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo-form"</span>&gt;</span> ... <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

$(<span class="hljs-string">"#demo-form"</span>).submitAsync()
.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"--送信完了--"</span>);
});

</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></span></pre>


<p>返り値は $.ajax() なので、then/done 等で結果を受け取ることができます。 引数には $.ajax() のオプションを渡すことができます。</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$(<span class="hljs-string">"#demo-form"</span>).submitAsync({
    <span class="hljs-attr">url</span>: <span class="hljs-string">"/api/foo"</span>,
    <span class="hljs-attr">dataType</span>: <span class="hljs-string">"jsonp"</span>
})
.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{ ... });
</code></span></pre>


<p>送信先のURLは通常 action 属性が使用されますが、引数のオプションで上書きする事もできます。 リクエストメソッド（&#8221;type&#8221;）も同様。</p>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.fn.submitAsync = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">options</span>)</span>{
    <span class="hljs-keyword">var</span> props = $.extend({
        <span class="hljs-attr">url</span>: <span class="hljs-keyword">this</span>.prop(<span class="hljs-string">"action"</span>),
        <span class="hljs-attr">type</span>: <span class="hljs-keyword">this</span>.prop(<span class="hljs-string">"method"</span>),
        <span class="hljs-attr">data</span>: <span class="hljs-keyword">this</span>.serializeObject()
    }, options);
    <span class="hljs-keyword">return</span> $.ajax(props);
};
</code></span></pre>


<p>Form の属性を読んで $.ajax() するだけの簡単なお仕事ですね。なくてもまったく困りません。 尚、内部で先に紹介した <a href="2016/12/18/ac2016-18.html">$.fn.serializeObject()</a> を使用しています。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (20) &#034;$.series&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/20/ac2016-20.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Tue, 20 Dec 2016 00:14:47 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4298</guid>

					<description><![CDATA[$.series() は、連鎖的に直列処理を実行していく関数です。 $.series(callback, callback, &#8230;) 使い方 渡した関数が返す値によって、次の処理までの挙動が変わります。 $.s [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.series()</strong> は、連鎖的に直列処理を実行していく関数です。</p>



<span id="more-4298"></span>



<h2 class="wp-block-heading">$.series(callback, callback, &#8230;)</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// 引数で渡した関数を順番に呼んでいきます</span>
$.series(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Process: 1"</span>);
        <span class="hljs-comment">// 数値（ミリ秒）を返すとその時間分次の処理を遅延させます</span>
        <span class="hljs-keyword">return</span> <span class="hljs-number">1000</span>;
    },
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Process: 2"</span>);
        <span class="hljs-comment">// 何も返さない（undefined）場合は `return 1;` と同じ</span>
    },
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-comment">// Deferredオブジェクトを返すと処理完了時に次の処理に移行します</span>
        <span class="hljs-keyword">return</span> $.ajax({<span class="hljs-attr">url</span>: <span class="hljs-string">"/api"</span>}).done(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Process: 3"</span>);
        });
    },
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-comment">// false を返すとそこで処理を中断して reject します</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
)
.then(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"--処理完了--"</span>);
    },
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"--途中で処理が中断されました--"</span>);
    }
);
</code></span></pre>


<p>渡した関数が返す値によって、次の処理までの挙動が変わります。</p>



<ul class="wp-block-list">
<li>数値 : 数値（ミリ秒）待機してから次の処理へ</li>



<li>Deferred : resolveされてから次の処理へ</li>



<li>false : 一連の処理を中断してrejectする</li>



<li>undefined : 何も返さない場合は 1 を返した場合と同じ</li>
</ul>



<p><strong>$.series()</strong> は Deferred を返すので、完了・失敗を <strong>then()</strong> 等で受け取る事ができます。</p>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.series = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">var</span> df = $.Deferred(),
        args = <span class="hljs-built_in">arguments</span>,
        i = <span class="hljs-number">-1</span>,
        timer = <span class="hljs-literal">null</span>,
        run;

    run = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">var</span> r;

        clearTimeout(timer);
        i += <span class="hljs-number">1</span>;
        <span class="hljs-keyword">if</span>(i &gt;= args.length){
            <span class="hljs-keyword">return</span> df.resolve();
        }
        r = args&#91;i]();
        <span class="hljs-keyword">if</span>(<span class="hljs-literal">false</span> === r){
            df.reject();
        }
        r = (r === <span class="hljs-keyword">void</span> <span class="hljs-number">0</span>) ? <span class="hljs-number">1</span> : r;
        <span class="hljs-keyword">switch</span>($.type(r)){
            <span class="hljs-keyword">case</span> <span class="hljs-string">"number"</span>: timer = setTimeout(run, r); <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"object"</span>:
                <span class="hljs-keyword">if</span>($.isFunction(r.then)){
                    r.then(run ,<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
                        df.reject();
                    });
                }
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>: <span class="hljs-keyword">break</span>;
        }
    }

    run();

    <span class="hljs-keyword">return</span> df;
};
</code></span></pre>


<p>Cに必要なAとBをやって、Dに必要なCをやってからDやって…というような感じに連鎖的に直列処理したい時や、 タイムラインで組んだアニメーション等が作れそうですね。</p>



<p>普通に <strong>Deferred</strong> 等で繋いでいっても良いんですが、コードが見づらくなってしまうので、 気持ちよく書きたいがためにうまれた関数です。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (19) &#034;$.fn.extract&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/19/ac2016-19.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Mon, 19 Dec 2016 00:13:18 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4294</guid>

					<description><![CDATA[$.fn.extract() は、非Form要素の内容をシリアライズする関数です。 $.fn.extract(asArray) 使い方 基本的な挙動は先に紹介した $.fn.serializeObject と同じです。  [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.fn.extract()</strong> は、非Form要素の内容をシリアライズする関数です。</p>



<span id="more-4294"></span>



<h2 class="wp-block-heading">$.fn.extract(asArray)</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"john"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"23"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

$(<span class="hljs-string">"#demo"</span>).extract();
<span class="hljs-comment">/* =&gt; {
    name: "john",
    age: 23
} */</span>

<span class="hljs-comment">// 引数にtrueを渡すと配列で返します</span>
$(<span class="hljs-string">"#demo"</span>).extract(<span class="hljs-literal">true</span>);
<span class="hljs-comment">/* =&gt; &#91;
    { key: "name", value: "john" },
    { key: "age", value: "23" }
] */</span>

</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></span></pre>


<p>基本的な挙動は先に紹介した <a href="/2016/12/18/ac2016-18.html">$.fn.serializeObject</a> と同じです。 オブジェクトではなく配列で受け取りたい場合は引数に <strong>true</strong> を渡します。</p>



<p>ちなみに、<strong>$.fn.serialize()</strong> や <strong>$.fn.serializeArray()</strong> は、非Form要素で使用しても空の文字列・配列を返します。 （後述にもありますが、それが正しいと思います）</p>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.fn.extract = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">asArray</span>)</span>{
    <span class="hljs-keyword">var</span> list = &#91;], data = {};
    <span class="hljs-keyword">this</span>.find(<span class="hljs-string">"input&#91;name], select&#91;name], textarea&#91;name]"</span>).each(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">var</span> name = <span class="hljs-keyword">this</span>.name;
        <span class="hljs-keyword">if</span>(&#91;<span class="hljs-string">"radio"</span>, <span class="hljs-string">"checkbox"</span>].indexOf(<span class="hljs-keyword">this</span>.type) &gt;= <span class="hljs-number">0</span>){
            <span class="hljs-keyword">return</span> ! <span class="hljs-keyword">this</span>.checked ? <span class="hljs-literal">null</span> : list.push({
                <span class="hljs-attr">name</span>: name,
                <span class="hljs-attr">value</span>: <span class="hljs-keyword">this</span>.value
            });
        }
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">this</span>.nodeName === <span class="hljs-string">"SELECT"</span>){
            <span class="hljs-keyword">return</span> $(<span class="hljs-keyword">this</span>).find(<span class="hljs-string">"option:selected"</span>).each(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
                list.push({
                    <span class="hljs-attr">name</span>: name,
                    <span class="hljs-attr">value</span>: <span class="hljs-keyword">this</span>.value
                });
            });
        }
        list.push({
            <span class="hljs-attr">name</span>: name,
            <span class="hljs-attr">value</span>: <span class="hljs-keyword">this</span>.value
        });
    });
    <span class="hljs-keyword">if</span>(asArray){
        <span class="hljs-keyword">return</span> list;
    }
    list.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
        <span class="hljs-keyword">if</span>(data&#91;item.name] !== <span class="hljs-keyword">void</span> <span class="hljs-number">0</span>){
            <span class="hljs-keyword">if</span>($.type(data&#91;item.name]) !== <span class="hljs-string">"array"</span>){
                data&#91;item.name] = &#91;data&#91;item.name]];
            }
            data&#91;item.name].push(item.value);
            <span class="hljs-keyword">return</span>;
        }
        data&#91;item.name] = item.value;
    });
    <span class="hljs-keyword">return</span> data;
};
</code></span></pre>


<p>オブジェクトで返すのをデフォルトとしている理由は、 わたし自身が基本的にオブジェクトで受け取りたいと思っているからです。</p>



<h2 class="wp-block-heading">存在意義</h2>



<p>なお、この関数の存在意義はあまり<strong>ありません</strong>。 form でマークアップすれば済む話ですし、そうすべきでしょう。 どうしてもレイアウトの都合で form の外に input を置かなければいけない場合は、 HTML5の form 属性で親となる form を指定してやれば対応可能です。</p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo-form"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"john"</span> <span class="hljs-attr">form</span>=<span class="hljs-string">"demo-form"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

$(<span class="hljs-string">"#demo-form"</span>).serialize(); <span class="hljs-comment">// =&gt; "name=john"</span>

</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></span></pre>


<p>こうすれば、$.fn.serialize/serializeArray() でもシリアライズする事ができ、仕様にも則っていますね。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (18) &#034;$.fn.serializeObject&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/18/ac2016-18.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Sat, 17 Dec 2016 23:57:29 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4291</guid>

					<description><![CDATA[$.fn.serializeObject() は、フォーム要素をシリアライズして、オブジェクトで返す関数です。 jQueryには文字列で返す $.fn.serialize() や、 配列で返す $.fn.serializ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.fn.serializeObject()</strong> は、フォーム要素をシリアライズして、オブジェクトで返す関数です。 jQueryには文字列で返す <a href="http://api.jquery.com/serialize">$.fn.serialize()</a> や、 配列で返す <a href="http://api.jquery.com/serializeArray">$.fn.serializeArray()</a> がありますが、そのオブジェクト版です。</p>



<span id="more-4291"></span>



<h2 class="wp-block-heading">$.fn.serializeObject()</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo-form"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"John"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"23"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"gender"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"male"</span> <span class="hljs-attr">checked</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"gender"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"female"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

$(<span class="hljs-string">"#demo-form"</span>).serializeObject();
<span class="hljs-comment">/* =&gt; {
    name: "John",
    age: 23,
    gender: "male"
} */</span>

</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></span></pre>


<p>複数選択された項目は、値が配列になります。</p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo-form"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"red"</span> <span class="hljs-attr">checked</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"green"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"blue"</span> <span class="hljs-attr">checked</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

$(<span class="hljs-string">"#demo-form"</span>).serializeObject();
<span class="hljs-comment">/* =&gt; {
    color: &#91;"red", "blue"]
} */</span>

</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></span></pre>


<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.fn.serializeObject = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">var</span> vars = {};
    <span class="hljs-keyword">this</span>.serializeArray().forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
        <span class="hljs-keyword">if</span>(item.name <span class="hljs-keyword">in</span> vars){
            <span class="hljs-keyword">if</span>(! $.isArray(vars&#91;item.name])){
                vars&#91;item.name] = &#91;vars&#91;item.name]];
            }
            vars&#91;item.name].push(item.value);
            <span class="hljs-keyword">return</span>;
        }
        vars&#91;item.name] = item.value;
    });
    <span class="hljs-keyword">return</span> vars;
};
</code></span></pre>


<p><strong>$.fn.serializeArray()</strong> が返す配列を読んでオブジェクトに変えているだけです。</p>



<p>Formの内容を非同期でPOSTしたい時などに使えるかもしれませんが、それはまた別の関数の話。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (17) &#034;$.scrollTo&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/17/ac2016-17.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Sat, 17 Dec 2016 02:30:48 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4282</guid>

					<description><![CDATA[$.scrollTo() は、ページあるいは要素の中身をアニメーションでスクロールしてくれる、よくある関数です。 $.scrollTo(dest, offset, options, selector) 使い方 なお、縦ス [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.scrollTo()</strong> は、ページあるいは要素の中身をアニメーションでスクロールしてくれる、よくある関数です。</p>



<span id="more-4282"></span>



<h2 class="wp-block-heading">$.scrollTo(dest, offset, options, selector)</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// ページの先頭に戻る</span>
$.scrollTo(<span class="hljs-number">0</span>);

<span class="hljs-comment">// "#destination" 要素の40px上に1秒かけてスクロールする</span>
$.scrollTo(<span class="hljs-string">"#destination"</span>, <span class="hljs-number">-40</span>, {
    <span class="hljs-attr">duration</span>: <span class="hljs-number">1000</span>
});

<span class="hljs-comment">// "#section-01" の位置まで移動して、完了時に location.hash を書き換える</span>
$.scrollTo(<span class="hljs-string">"#section-01"</span>, <span class="hljs-number">0</span>, {
    <span class="hljs-attr">done</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        location.hash = <span class="hljs-string">"#section-01"</span>;
    }
});

<span class="hljs-comment">// #scrollArea の中身を、#destPosition の位置までスクロールする</span>
$.scrollTo(<span class="hljs-string">"#destPosition"</span>, <span class="hljs-number">0</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"#scrollArea"</span>);
</code></span></pre>


<ul class="wp-block-list">
<li>到達点の指定（第一引数）は、数値かセレクタで渡します。</li>



<li>非数値である場合は、セレクタとみなしてその要素の位置までスクロールします。 </li>



<li>options はjQueryのanimate関数にそのまま渡されます</li>



<li>第四引数は、スクロールをする要素のセレクタです。（デフォルトは &#8220;html,body&#8221;）</li>
</ul>



<p>なお、縦スクロールの事しか考えていない点はご容赦ください。</p>



<h3 class="wp-block-heading">注意したい点</h3>



<p>ページ内にある要素（&#8221;html,body&#8221; ではない要素）のスクロールをおこなう場合は、 その要素の position は &#8220;static&#8221; 以外でないといけない点に注意が必要です。 コンテキストを生成しないと親のコンテキストから位置を計算してしまうので、到達点の計算がズレズレになってしまいますね。 （到達点を数値で指定する場合はその限りではありません）</p>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.scrollTo = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">dest, offset, options, selector</span>)</span>{
    <span class="hljs-keyword">if</span>($.type(dest) !== <span class="hljs-string">"number"</span>){
        dest = $(dest)&#91;selector === <span class="hljs-keyword">void</span> <span class="hljs-number">0</span> ? <span class="hljs-string">"offset"</span> : <span class="hljs-string">"position"</span>]().top;
    }
    offset = offset || <span class="hljs-number">0</span>;
    options = options || {};
    selector = selector || <span class="hljs-string">"html,body"</span>;
    $(selector).animate({
        <span class="hljs-attr">scrollTop</span>: dest + offset
    }, options);
};
</code></span></pre>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>細かすぎて伝わらないjQuery拡張 (16) &#034;$.render&#034; &#8211; Advent Calendar 2016</title>
		<link>https://blog.mach3.jp/2016/12/16/ac2016-16.html</link>
		
		<dc:creator><![CDATA[mach3]]></dc:creator>
		<pubDate>Fri, 16 Dec 2016 01:40:25 +0000</pubDate>
				<category><![CDATA[Laboratory]]></category>
		<category><![CDATA[Advent Calendar 2016]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://blog.mach3.jp/?p=4277</guid>

					<description><![CDATA[$.render() は単機能のテンプレート関数です。 エンジンと呼称するにはおこがましいくらい単機能です。 $.render(template, data) 使い方 テンプレートの体裁は Mustache っぽいですが [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://goo.gl/ad8zjX" alt=""/></figure>



<p></p>



<p><strong>$.render()</strong> は単機能のテンプレート関数です。 エンジンと呼称するにはおこがましいくらい単機能です。</p>



<span id="more-4277"></span>



<h2 class="wp-block-heading">$.render(template, data)</h2>



<h3 class="wp-block-heading">使い方</h3>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// template と data を渡すと即時展開</span>
$.render(<span class="hljs-string">"わたしは{{name}}、{{age}}歳だ！"</span>, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"ジョン"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">23</span>
});
<span class="hljs-comment">// =&gt; "わたしはジョン、23歳だ！"</span>

<span class="hljs-comment">// template のみの場合は関数を返す</span>
<span class="hljs-keyword">var</span> render = $.render(<span class="hljs-string">"わたしは{{name}}、{{age}}歳だ！"</span>);
render({<span class="hljs-attr">name</span>: <span class="hljs-string">"ジョン"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">23</span>}); <span class="hljs-comment">// =&gt; "わたしはジョン、23歳だ！"</span>

<span class="hljs-comment">// キー名はドットシンタックスが使える</span>
$.render(<span class="hljs-string">"{{user.name}}, {{user.age}}"</span>, {
    <span class="hljs-attr">user</span>: {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"john"</span>,
        <span class="hljs-attr">age</span>: <span class="hljs-number">23</span>
    }
});
<span class="hljs-comment">// =&gt; "john, 23"</span>

<span class="hljs-comment">// {{key}} はHTMLをエスケープする</span>
<span class="hljs-comment">// {{{key}}} はHTMLをエスケープしない</span>
$.render(<span class="hljs-string">"{{content}}, {{{content}}}"</span>, {
    <span class="hljs-attr">content</span>: <span class="hljs-string">"&lt;script&gt;"</span>
});
<span class="hljs-comment">// =&gt; "&amp;lt;script&amp;gt;, &lt;script&gt;"</span>
</code></span></pre>


<ul class="wp-block-list">
<li>テンプレートとデータを渡してキーを基に差し替えて返します。</li>



<li>data を渡さないことで、<a href="https://lodash.com/docs/#template">_.template</a>のようにレンダー関数を返す事もできます。</li>



<li>キー名にはドットシンタックスが使えます。（先に紹介した <a href="/2016/12/05/ac2016-05.html">$.dig</a> を内部で使用）</li>



<li><strong>&#8220;{{key}}&#8221;</strong> はHTMLエスケープします。（先に紹介した <a href="/2016/12/06/ac2016-06.html">$.escapeHTML</a> を内部で使用）</li>



<li><strong>&#8220;{{{key}}}&#8221;</strong> はエスケープせずにそのまま出力します。</li>
</ul>



<p>テンプレートの体裁は <a href="https://mustache.github.io/">Mustache</a> っぽいですが、条件分岐やループ処理などは搭載していません。 本当にテンプレートに値をはめ込むだけの機能しかありません。 敢えて言わせていただくと、<strong>「MustacheなりHandlebarsをつかっておけ」</strong>で済む話ですね。</p>



<ul class="wp-block-list">
<li><a href="https://mustache.github.io/">{{ mustache }}</a></li>



<li><a href="http://handlebarsjs.com/">Handlebars.js: Minimal Templating on Steroids</a></li>
</ul>



<h2 class="wp-block-heading">コード</h2>


<pre class="wp-block-code"><span><code class="hljs language-javascript">$.render = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">template, data</span>)</span>{
    <span class="hljs-keyword">var</span> func = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">vars</span>)</span>{
        <span class="hljs-keyword">return</span> template.replace(<span class="hljs-regexp">/(&#91;\{]{2,3})(&#91;\w\.\-]+)(&#91;\}]{2,3})/g</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a,b,c</span>)</span>{
            <span class="hljs-keyword">var</span> value = $.dig(c, vars) || <span class="hljs-string">""</span>;
            value = (b.length &gt; <span class="hljs-number">2</span>) ? value : $.escapeHTML(value);
            <span class="hljs-keyword">return</span> value;
        });
    };
    <span class="hljs-keyword">return</span> data === <span class="hljs-keyword">void</span> <span class="hljs-number">0</span> ? func : func(data);
}
</code></span></pre>


<p>6年前に書いた以下のエントリーの物から余計な物を削って若干改修・簡略化した関数です。</p>



<ul class="wp-block-list">
<li><a href="https://blog.mach3.jp/2010/09/10/jquery-render-js.html">シンプルなjQueryテンプレートプラグインを書いてみる &#8211; Mach3.laBlog</a></li>
</ul>



<p>HTMLのテンプレートとして使うには力不足が否めない関数ですが、 URL文字列を組み立てたりするプレースホルダとしてなら、コード量少ないですし使い道があるかもしれませんね。 ないかもしれませんね。</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
